/**
 * 火星情报局后台管理系统
 * 
 * 本文件包含管理系统的通用JavaScript逻辑
 */

// 全局变量
let currentPage = 1;
let pageSize = 10;
let totalPages = 1;
let currentView = 'ai-roles';

// 获取保存的token (从多个存储源)
function getAuthToken() {
    let token = null;
    let source = '';
    
    // 按优先级检查各种存储
    if (localStorage && localStorage.getItem('adminToken')) {
        token = localStorage.getItem('adminToken');
        source = 'localStorage';
    } else if (sessionStorage && sessionStorage.getItem('adminToken')) {
        token = sessionStorage.getItem('adminToken');
        source = 'sessionStorage';
    } else {
        // 检查cookie
        const match = document.cookie.match(/adminToken=([^;]+)/);
        if (match) {
            token = match[1];
            source = 'cookies';
        }
    }
    
    if (token) {
        console.log(`从 ${source} 读取到token: ${token.substring(0, 15)}...`);
    } else {
        console.warn('未找到存储的token');
    }
    
    return token;
}

// 检查是否已登录
function checkAuth() {
    const token = getAuthToken();
    console.log('checkAuth 验证状态:', !!token);
    
    if (!token && !window.location.href.includes('login.html')) {
        // 未登录，重定向到登录页
        console.warn('未找到token，准备重定向到登录页');
        window.location.href = '/admin/login.html';
        return false;
    }
    return !!token;
}

// API请求封装
async function fetchAPI(url, method = 'GET', data = null) {
    const token = getAuthToken();
    const headers = {
        'Content-Type': 'application/json'
    };
    
    if (token) {
        headers['Authorization'] = `Bearer ${token}`;
        console.log(`发送API请求到 ${url}，带有Authorization头部`);
    } else {
        console.warn(`发送API请求到 ${url}，但未找到token`);
    }
    
    const options = {
        method,
        headers,
        credentials: 'same-origin'
    };
    
    if (data && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
        options.body = JSON.stringify(data);
    }
    
    try {
        console.log(`准备发送${method}请求到: ${url}`);
        const response = await fetch(url, options);
        console.log(`API响应状态: ${response.status}`);
        
        // 如果是200状态，直接处理
        if (response.status === 200) {
            console.log('✅ API请求成功，开始解析响应...');
        }
        
        // 处理401未授权错误
        if (response.status === 401) {
            console.error('API请求返回401未授权，清除token并重定向');
            clearAllTokens();
            showMessage('登录已过期，请重新登录', 'error');
            setTimeout(() => {
                window.location.href = '/admin/login.html';
            }, 1500);
            return null;
        }
        
        // 处理403权限错误
        if (response.status === 403) {
            console.error('API请求返回403权限不足');
            showMessage('权限不足，无法执行此操作', 'error');
            return { error: '权限不足', status: 403 };
        }
        
        // 处理404错误
        if (response.status === 404) {
            console.error(`API请求返回404 Not Found: ${url}`);
            return { error: `接口不存在: ${url.split('?')[0]}`, status: 404 };
        }
        
        // 处理500服务器错误
        if (response.status >= 500) {
            console.error(`API请求返回服务器错误: ${response.status}`);
            const errorData = await response.json().catch(() => ({ error: '服务器内部错误' }));
            showMessage(errorData.message || '服务器内部错误，请稍后重试', 'error');
            return { error: errorData.message || '服务器内部错误', status: response.status };
        }
        
        const responseData = await response.json().catch(e => {
            console.error('解析响应JSON失败:', e);
            return { error: '无法解析服务器响应' };
        });
        
        console.log('📦 解析后的响应数据:', responseData);
        return responseData;
    } catch (error) {
        console.error('API请求错误:', error);
        showMessage('网络请求失败，请检查网络连接', 'error');
        return { error: '网络请求失败，请检查网络连接' };
    }
}

// 清除所有存储的token
function clearAllTokens() {
    if (localStorage) localStorage.removeItem('adminToken');
    if (sessionStorage) sessionStorage.removeItem('adminToken');
    document.cookie = 'adminToken=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT';
}

// 显示消息提示
function showMessage(message, type = 'info') {
    // 创建消息元素
    const messageEl = document.createElement('div');
    messageEl.className = `message message-${type}`;
    messageEl.textContent = message;
    
    // 添加样式
    messageEl.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 12px 20px;
        border-radius: 4px;
        color: white;
        font-weight: 500;
        z-index: 10000;
        max-width: 300px;
        word-wrap: break-word;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        transition: all 0.3s ease;
    `;
    
    // 根据类型设置背景色
    switch (type) {
        case 'success':
            messageEl.style.backgroundColor = '#52c41a';
            break;
        case 'error':
            messageEl.style.backgroundColor = '#ff4d4f';
            break;
        case 'warning':
            messageEl.style.backgroundColor = '#faad14';
            break;
        default:
            messageEl.style.backgroundColor = '#1890ff';
    }
    
    document.body.appendChild(messageEl);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (messageEl.parentNode) {
            messageEl.style.opacity = '0';
            messageEl.style.transform = 'translateX(100%)';
            setTimeout(() => {
                messageEl.parentNode.removeChild(messageEl);
            }, 300);
        }
    }, 3000);
}

// 初始化管理界面
function initDashboard() {
    console.log('开始初始化管理界面');
    if (!checkAuth()) {
        console.error('认证检查失败，不进行初始化');
        return;
    }
    
    console.log('认证检查通过，开始设置事件监听');
    
    // 初始化导航栏点击事件
    document.querySelectorAll('.main-nav a').forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const viewId = this.getAttribute('data-view');
            switchView(viewId);
        });
    });
    
    // 初始化退出登录按钮
    document.getElementById('logoutBtn').addEventListener('click', function() {
        console.log('用户点击退出登录');
        clearAllTokens();
        showMessage('已退出登录', 'success');
        setTimeout(() => {
            window.location.href = '/admin/login.html';
        }, 1000);
    });
    
    // 初始化搜索和筛选功能
    initSearchAndFilter();
    
    // 初始化创建AI角色按钮
    document.getElementById('createAiRoleBtn').addEventListener('click', showCreateAiRoleModal);
    
    // 初始化创建API密钥按钮
    document.getElementById('createApiKeyBtn').addEventListener('click', showCreateApiKeyModal);
    
    // 初始化API配置相关按钮
    if (document.getElementById('saveApiConfigBtn')) {
        document.getElementById('saveApiConfigBtn').addEventListener('click', saveApiConfig);
    }
    if (document.getElementById('loadCurrentConfigBtn')) {
        document.getElementById('loadCurrentConfigBtn').addEventListener('click', loadApiConfig);
    }
    if (document.getElementById('testAllKeysBtn')) {
        document.getElementById('testAllKeysBtn').addEventListener('click', testAllApiKeys);
    }
    if (document.getElementById('apiConfigForm')) {
        document.getElementById('apiConfigForm').addEventListener('submit', handleApiConfigSubmit);
    }
    
    // 初始化用户管理按钮
    document.getElementById('createUserBtn').addEventListener('click', showCreateUserModal);
    document.getElementById('batchDeleteUsersBtn').addEventListener('click', batchDeleteUsers);
    
    // 初始化刷新社区图片按钮
    document.getElementById('refreshSharedImagesBtn').addEventListener('click', function() {
        loadSharedImages();
    });
    
    // 初始化文件管理按钮
    document.getElementById('cleanupFilesBtn').addEventListener('click', previewCleanup);
    document.getElementById('refreshStatsBtn').addEventListener('click', loadFileStats);
    document.getElementById('previewCleanupBtn').addEventListener('click', previewCleanup);
    document.getElementById('executeCleanupBtn').addEventListener('click', executeCleanup);
    
    // 初始化模态框关闭按钮
    document.querySelectorAll('.close-btn, #cancelAiRoleBtn, #cancelApiKeyBtn, #cancelUserBtn, #closeUserDetailBtn').forEach(btn => {
        btn.addEventListener('click', function() {
            const modalId = this.closest('.modal').id;
            document.getElementById(modalId).style.display = 'none';
        });
    });
    
    // 初始化API密钥表单提交
    document.getElementById('apiKeyForm').addEventListener('submit', handleApiKeySubmit);
    
    // 初始化AI角色表单提交
    document.getElementById('aiRoleForm').addEventListener('submit', handleAiRoleSubmit);
    
    // 初始化用户表单提交
    document.getElementById('userForm').addEventListener('submit', handleUserSubmit);
    
    // 初始化用户详情编辑按钮
    document.getElementById('editUserFromDetailBtn').addEventListener('click', function() {
        const userId = document.getElementById('detailUserId').textContent;
        document.getElementById('userDetailModal').style.display = 'none';
        editUser(userId);
    });
    
    // 加载初始数据
    console.log('开始加载AI角色数据');
    loadAiRoles();
}

// 初始化搜索和筛选功能
function initSearchAndFilter() {
    // AI角色搜索
    const searchAiRole = document.getElementById('searchAiRole');
    const filterAiRoleType = document.getElementById('filterAiRoleType');
    
    if (searchAiRole) {
        searchAiRole.addEventListener('input', debounce(() => {
            currentPage = 1;
            loadAiRoles();
        }, 500));
    }
    
    if (filterAiRoleType) {
        filterAiRoleType.addEventListener('change', () => {
            currentPage = 1;
            loadAiRoles();
        });
    }
    
    // API密钥搜索
    const searchApiKey = document.getElementById('searchApiKey');
    const filterApiKeyProvider = document.getElementById('filterApiKeyProvider');
    const filterApiKeyStatus = document.getElementById('filterApiKeyStatus');
    
    if (searchApiKey) {
        searchApiKey.addEventListener('input', debounce(() => {
            currentPage = 1;
            loadApiKeys();
        }, 500));
    }
    
    if (filterApiKeyProvider) {
        filterApiKeyProvider.addEventListener('change', () => {
            currentPage = 1;
            loadApiKeys();
        });
    }
    
    if (filterApiKeyStatus) {
        filterApiKeyStatus.addEventListener('change', () => {
            currentPage = 1;
            loadApiKeys();
        });
    }
    
    // 用户搜索
    const searchUser = document.getElementById('searchUser');
    const filterUserRole = document.getElementById('filterUserRole');
    const filterUserStatus = document.getElementById('filterUserStatus');
    
    if (searchUser) {
        searchUser.addEventListener('input', debounce(() => {
            currentPage = 1;
            loadUsers();
        }, 500));
    }
    
    if (filterUserRole) {
        filterUserRole.addEventListener('change', () => {
            currentPage = 1;
            loadUsers();
        });
    }
    
    if (filterUserStatus) {
        filterUserStatus.addEventListener('change', () => {
            currentPage = 1;
            loadUsers();
        });
    }
    
    // 社区图片搜索
    const searchSharedImage = document.getElementById('searchSharedImage');
    const filterImageCategory = document.getElementById('filterImageCategory');
    const filterImageUser = document.getElementById('filterImageUser');
    
    if (searchSharedImage) {
        searchSharedImage.addEventListener('input', debounce(() => {
            currentPage = 1;
            loadSharedImages();
        }, 500));
    }
    
    if (filterImageCategory) {
        filterImageCategory.addEventListener('change', () => {
            currentPage = 1;
            loadSharedImages();
        });
    }
    
    if (filterImageUser) {
        filterImageUser.addEventListener('change', () => {
            currentPage = 1;
            loadSharedImages();
        });
    }
}

// 编辑API密钥
async function editApiKey(id) {
    try {
        const data = await fetchAPI(`/api/api-keys/${id}`);
        
        if (data && data.success) {
            const apiKey = data.data;
            
            // 填充表单
            document.getElementById('apiKeyId').value = apiKey.id;
            document.getElementById('apiKeyName').value = apiKey.name;
            document.getElementById('apiKeyProvider').value = apiKey.provider;
            document.getElementById('apiKeyValue').value = apiKey.api_key;
            document.getElementById('apiKeyDescription').value = apiKey.description || '';
            
            // 显示模态框
            document.getElementById('apiKeyModal').style.display = 'block';
            document.getElementById('apiKeyModalTitle').textContent = '编辑API密钥';
        } else {
            showMessage(data?.error || '获取API密钥信息失败', 'error');
        }
    } catch (error) {
        console.error('编辑API密钥异常:', error);
        showMessage('编辑API密钥异常', 'error');
    }
}

// 删除API密钥
async function deleteApiKey(id) {
    if (!confirm('确定要删除这个API密钥吗？')) {
        return;
    }
    
    try {
        const data = await fetchAPI(`/api/api-keys/${id}`, 'DELETE');
        
        if (data && data.success) {
            showMessage('API密钥删除成功', 'success');
            loadApiKeys(); // 刷新列表
        } else {
            showMessage(data?.error || '删除API密钥失败', 'error');
        }
    } catch (error) {
        console.error('删除API密钥异常:', error);
        showMessage('删除API密钥异常', 'error');
    }
}

// 切换API密钥状态
async function toggleApiKeyStatus(id) {
    try {
        const data = await fetchAPI(`/api/api-keys/${id}/toggle`, 'PATCH');
        
        if (data && data.success) {
            showMessage('API密钥状态更新成功', 'success');
            loadApiKeys(); // 刷新列表
        } else {
            showMessage(data?.error || '更新API密钥状态失败', 'error');
        }
    } catch (error) {
        console.error('更新API密钥状态异常:', error);
        showMessage('更新API密钥状态异常', 'error');
    }
}

// 查看社区图片详情
async function viewSharedImage(id) {
    try {
        const data = await fetchAPI(`/api/shared-images/${id}`);
        
        if (data && data.success) {
            const image = data.data;
            
            // 创建查看模态框
            const modal = document.createElement('div');
            modal.className = 'modal';
            modal.innerHTML = `
                <div class="modal-content modal-large">
                    <div class="modal-header">
                        <h3>图片详情</h3>
                        <span class="close">&times;</span>
                    </div>
                    <div class="modal-body">
                        <div class="image-detail-container">
                            <div class="image-preview">
                                <img id="sharedImagePreview" src="${image.image_path}" alt="${image.title}" style="max-width: 100%; max-height: 60vh; object-fit: contain;">
                            </div>
                            <div class="image-info">
                                <div class="info-item">
                                    <label>标题:</label>
                                    <span id="sharedImageTitle" style="display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis;">${image.title}</span>
                                </div>
                                <div class="info-item">
                                    <label>描述:</label>
                                    <p id="sharedImageDescription">${image.description || '无'}</p>
                                </div>
                                <div class="info-item">
                                    <label>分类:</label>
                                    <span id="sharedImageCategory">${image.category}</span>
                                </div>
                                <div class="info-item">
                                    <label>标签:</label>
                                    <div id="sharedImageTags" class="tags-container">
                                        ${image.tags ? image.tags.split(',').map(tag => `<span class="tag">${tag.trim()}</span>`).join('') : '无'}
                                    </div>
                                </div>
                                <div class="info-item">
                                    <label>上传用户:</label>
                                    <span id="sharedImageUser">${image.username || '未知'}</span>
                                </div>
                                <div class="info-item">
                                    <label>AI角色:</label>
                                    <span id="sharedImageAiRole">${image.ai_role_name || '未知'}</span>
                                </div>
                                <div class="info-item">
                                    <label>点赞数:</label>
                                    <span id="sharedImageLikes">${image.like_count || 0}</span>
                                </div>
                                <div class="info-item">
                                    <label>创建时间:</label>
                                    <span id="sharedImageCreatedAt">${new Date(image.created_at).toLocaleString()}</span>
                                </div>
                                <div class="info-item">
                                    <label>操作:</label>
                                    <div class="image-actions">
                                        <button id="deleteSharedImageBtn" class="btn-danger">删除图片</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            modal.style.display = 'block';
            
            // 添加图片点击放大功能
            const previewImg = document.getElementById('sharedImagePreview');
            previewImg.addEventListener('click', function() {
                const fullscreenModal = document.createElement('div');
                fullscreenModal.className = 'fullscreen-modal';
                fullscreenModal.innerHTML = `
                    <div class="fullscreen-content">
                        <img src="${image.image_path}" alt="${image.title}" style="max-width: 100%; max-height: 100%; object-fit: contain;">
                        <span class="close-fullscreen">&times;</span>
                    </div>
                `;
                document.body.appendChild(fullscreenModal);
                
                // 关闭全屏模态框
                fullscreenModal.querySelector('.close-fullscreen').addEventListener('click', function() {
                    document.body.removeChild(fullscreenModal);
                });
                
                fullscreenModal.addEventListener('click', function(e) {
                    if (e.target === fullscreenModal) {
                        document.body.removeChild(fullscreenModal);
                    }
                });
            });
            
            // 添加关闭事件
            modal.querySelector('.close').addEventListener('click', function() {
                document.body.removeChild(modal);
            });
            
            modal.addEventListener('click', function(e) {
                if (e.target === modal) {
                    document.body.removeChild(modal);
                }
            });
        } else {
            showMessage(data?.error || '获取图片详情失败', 'error');
        }
    } catch (error) {
        console.error('查看图片详情异常:', error);
        showMessage('查看图片详情异常', 'error');
    }
}

// 删除社区图片
async function deleteSharedImage(id) {
    if (!confirm('确定要删除这张图片吗？')) {
        return;
    }
    
    try {
        const data = await fetchAPI(`/api/shared-images/${id}`, 'DELETE');
        
        if (data && data.success) {
            showMessage('图片删除成功', 'success');
            loadSharedImages(); // 刷新列表
        } else {
            showMessage(data?.error || '删除图片失败', 'error');
        }
    } catch (error) {
        console.error('删除图片异常:', error);
        showMessage('删除图片异常', 'error');
    }
}

// 显示创建API密钥模态框
function showCreateApiKeyModal() {
    // 重置表单
    document.getElementById('apiKeyForm').reset();
    document.getElementById('apiKeyId').value = '';
    
    // 显示模态框
    document.getElementById('apiKeyModal').style.display = 'block';
    document.getElementById('apiKeyModalTitle').textContent = '创建API密钥';
}

// 显示加载状态
function showLoading(elementId) {
    const element = document.getElementById(elementId);
    if (element) {
        element.innerHTML = '<tr><td colspan="100%" style="text-align: center; padding: 20px;">加载中...</td></tr>';
    }
}

// 显示消息提示
function showMessage(message, type = 'info') {
    // 创建消息元素
    const messageEl = document.createElement('div');
    messageEl.className = `message message-${type}`;
    messageEl.textContent = message;
    
    // 添加样式
    messageEl.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 12px 20px;
        border-radius: 4px;
        color: white;
        font-weight: 500;
        z-index: 10000;
        max-width: 300px;
        word-wrap: break-word;
    `;
    
    // 根据类型设置背景色
    switch (type) {
        case 'success':
            messageEl.style.backgroundColor = '#10b981';
            break;
        case 'error':
            messageEl.style.backgroundColor = '#ef4444';
            break;
        case 'warning':
            messageEl.style.backgroundColor = '#f59e0b';
            break;
        default:
            messageEl.style.backgroundColor = '#3b82f6';
    }
    
    // 添加到页面
    document.body.appendChild(messageEl);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (messageEl.parentNode) {
            messageEl.parentNode.removeChild(messageEl);
        }
    }, 3000);
}

// 清除所有token
function clearAllTokens() {
    // 清除localStorage
    localStorage.removeItem('adminToken');
    localStorage.removeItem('token');
    
    // 清除sessionStorage
    sessionStorage.removeItem('adminToken');
    sessionStorage.removeItem('token');
    
    // 清除cookie
    document.cookie = 'adminToken=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
    document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
}

// 删除AI角色
async function deleteAiRole(id) {
    if (!confirm('确定要删除这个AI角色吗？')) {
        return;
    }
    
    try {
        const data = await fetchAPI(`/api/airoles/${id}`, 'DELETE');
        
        if (data && data.success) {
            showMessage('AI角色删除成功', 'success');
            loadAiRoles(); // 刷新列表
        } else {
            showMessage(data?.error || '删除AI角色失败', 'error');
        }
    } catch (error) {
        console.error('删除AI角色异常:', error);
        showMessage('删除AI角色异常', 'error');
    }
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 切换视图
function switchView(viewId) {
    currentView = viewId;
    
    // 更新导航栏激活状态
    document.querySelectorAll('.main-nav li').forEach(item => {
        item.classList.remove('active');
    });
    document.querySelector(`.main-nav a[data-view="${viewId}"]`).parentElement.classList.add('active');
    
    // 更新页面标题
    const titles = {
        'ai-roles': 'AI角色管理',
        'api-keys': 'API密钥管理',
        'api-config': 'API密钥配置',
        'users': '用户管理',
        'shared-images': '社区图片管理',
        'file-management': '文件管理',
        'system': '系统设置'
    };
    document.getElementById('pageTitle').textContent = titles[viewId];
    
    // 显示/隐藏相应的按钮
    document.getElementById('createAiRoleBtn').style.display = viewId === 'ai-roles' ? 'block' : 'none';
    document.getElementById('createApiKeyBtn').style.display = viewId === 'api-keys' ? 'block' : 'none';
    document.getElementById('saveApiConfigBtn').style.display = viewId === 'api-config' ? 'block' : 'none';
    document.getElementById('createUserBtn').style.display = viewId === 'users' ? 'block' : 'none';
    document.getElementById('batchDeleteUsersBtn').style.display = viewId === 'users' ? 'block' : 'none';
    document.getElementById('refreshSharedImagesBtn').style.display = viewId === 'shared-images' ? 'block' : 'none';
    document.getElementById('cleanupFilesBtn').style.display = viewId === 'file-management' ? 'block' : 'none';
    document.getElementById('refreshStatsBtn').style.display = viewId === 'file-management' ? 'block' : 'none';
    
    // 隐藏所有视图，显示当前视图
    document.querySelectorAll('.view').forEach(view => {
        view.classList.remove('active');
    });
    document.getElementById(`${viewId}-view`).classList.add('active');
    
    // 加载相应的数据
    switch (viewId) {
        case 'ai-roles':
            loadAiRoles();
            break;
        case 'api-keys':
            loadApiKeys();
            break;
        case 'api-config':
            loadApiConfig();
            break;
        case 'api-config':
            loadApiConfig();
            break;
        case 'api-config':
            loadApiConfig();
            break;
        case 'users':
            loadUsers();
            break;
        case 'shared-images':
            loadSharedImages();
            break;
        case 'file-management':
            loadFileStats();
            break;
        case 'system':
            loadSystemSettings();
            break;
    }
}

// 加载AI角色数据
async function loadAiRoles() {
    try {
        showLoading('aiRolesTableBody');
        
        const searchTerm = document.getElementById('searchAiRole')?.value || '';
        const type = document.getElementById('filterAiRoleType')?.value || '';
        
        const queryParams = new URLSearchParams();
        if (searchTerm) queryParams.append('search', searchTerm);
        if (type) queryParams.append('type', type);
        queryParams.append('page', currentPage);
        queryParams.append('limit', pageSize);
        
        const data = await fetchAPI(`/api/airoles?${queryParams.toString()}`);
        
        if (data && !data.error) {
            if (Array.isArray(data)) {
                renderAiRolesTable(data);
                renderPagination(data.length, 'aiRolesPagination');
            } else if (data.success && Array.isArray(data.data)) {
                renderAiRolesTable(data.data);
                renderPagination(data.data.length, 'aiRolesPagination');
            } else {
                renderAiRolesTable([]);
                showMessage('未找到AI角色数据', 'warning');
            }
        } else {
            renderAiRolesTable([]);
            showMessage(data?.error || '加载AI角色数据失败', 'error');
        }
    } catch (error) {
        console.error('加载AI角色数据异常:', error);
        renderAiRolesTable([]);
        showMessage('加载AI角色数据异常', 'error');
    }
}

// 显示加载状态
function showLoading(containerId) {
    const container = document.getElementById(containerId);
    if (container) {
        container.innerHTML = `
            <tr>
                <td colspan="7" style="text-align: center; padding: 40px;">
                    <div class="loading-spinner"></div>
                    <div style="margin-top: 10px;">加载中...</div>
                </td>
            </tr>
        `;
    }
}

// 渲染AI角色表格
function renderAiRolesTable(roles) {
    const tbody = document.getElementById('aiRolesTableBody');
    tbody.innerHTML = '';
    
    if (roles.length === 0) {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td colspan="7" style="text-align: center;">暂无数据</td>
        `;
        tbody.appendChild(row);
        return;
    }
    
    // 角色类型映射
    const typeMap = {
        'assistant': '通用助手',
        'tutor': '教育导师',
        'entertainment': '娱乐伙伴',
        'other': '其他类型'
    };
    
    roles.forEach(role => {
        // 使用内嵌的SVG作为默认头像，避免404错误
        const defaultAvatar = `data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="36" height="36"><circle cx="12" cy="7" r="5" fill="%23718096"/><path d="M21,24v-5c0-4.4-3.6-8-8-8h-2c-4.4,0-8,3.6-8,8v5" fill="%23718096"/></svg>`;
        
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${role.id}</td>
            <td>
                <div class="avatar-cell">
                    <img src="${role.avatar || defaultAvatar}" alt="${role.name}" 
                         onerror="this.onerror=null; this.src='${defaultAvatar}'">
                </div>
            </td>
            <td>${role.name}</td>
            <td>${typeMap[role.type] || role.type}</td>
            <td>${role.api_provider}</td>
            <td>${new Date(role.created_at).toLocaleString()}</td>
            <td class="action-cell">
                <button class="btn-action btn-view" data-id="${role.id}">查看</button>
                <button class="btn-action btn-edit" data-id="${role.id}">编辑</button>
                <button class="btn-action btn-delete" data-id="${role.id}">删除</button>
            </td>
        `;
        tbody.appendChild(row);
    });
    
    // 添加按钮事件
    document.querySelectorAll('#aiRolesTableBody .btn-view').forEach(btn => {
        btn.addEventListener('click', function() {
            const id = this.getAttribute('data-id');
            viewAiRole(id);
        });
    });
    
    document.querySelectorAll('#aiRolesTableBody .btn-edit').forEach(btn => {
        btn.addEventListener('click', function() {
            const id = this.getAttribute('data-id');
            editAiRole(id);
        });
    });
    
    document.querySelectorAll('#aiRolesTableBody .btn-delete').forEach(btn => {
        btn.addEventListener('click', function() {
            const id = this.getAttribute('data-id');
            deleteAiRole(id);
        });
    });
}

// 加载API密钥数据
async function loadApiKeys() {
    try {
        showLoading('apiKeysTableBody');
        
        const searchTerm = document.getElementById('searchApiKey')?.value || '';
        const provider = document.getElementById('filterApiKeyProvider')?.value || '';
        const status = document.getElementById('filterApiKeyStatus')?.value || '';
        
        const queryParams = new URLSearchParams();
        if (searchTerm) queryParams.append('search', searchTerm);
        if (provider) queryParams.append('provider', provider);
        if (status) queryParams.append('status', status);
        queryParams.append('page', currentPage);
        queryParams.append('limit', pageSize);
        
        const data = await fetchAPI(`/api/api-keys?${queryParams.toString()}`);
        
        if (data && !data.error) {
            if (data.success && Array.isArray(data.data)) {
                renderApiKeysTable(data.data);
                renderPagination(data.data.length, 'apiKeysPagination');
            } else {
                renderApiKeysTable([]);
                showMessage('未找到API密钥数据', 'warning');
            }
        } else {
            renderApiKeysTable([]);
            showMessage(data?.error || '加载API密钥数据失败', 'error');
        }
    } catch (error) {
        console.error('加载API密钥数据异常:', error);
        renderApiKeysTable([]);
        showMessage('加载API密钥数据异常', 'error');
    }
}

// 渲染API密钥表格
function renderApiKeysTable(apiKeys) {
    const tbody = document.getElementById('apiKeysTableBody');
    tbody.innerHTML = '';
    
    if (apiKeys.length === 0) {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td colspan="8" style="text-align: center;">暂无数据</td>
        `;
        tbody.appendChild(row);
        return;
    }
    
    apiKeys.forEach(apiKey => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${apiKey.id}</td>
            <td>${apiKey.name}</td>
            <td>${apiKey.provider}</td>
            <td>
                <span class="status-badge ${apiKey.is_active ? 'status-active' : 'status-inactive'}">
                    ${apiKey.is_active ? '启用' : '禁用'}
                </span>
            </td>
            <td>${apiKey.usage_count || 0}</td>
            <td>${apiKey.last_used_at ? new Date(apiKey.last_used_at).toLocaleString() : '从未使用'}</td>
            <td>${new Date(apiKey.created_at).toLocaleString()}</td>
            <td class="action-cell">
                <button class="btn-action btn-edit" data-id="${apiKey.id}">编辑</button>
                <button class="btn-action btn-delete" data-id="${apiKey.id}">删除</button>
                <button class="btn-action ${apiKey.is_active ? 'btn-disable' : 'btn-enable'}" data-id="${apiKey.id}">
                    ${apiKey.is_active ? '禁用' : '启用'}
                </button>
            </td>
        `;
        tbody.appendChild(row);
    });
    
    // 添加按钮事件
    document.querySelectorAll('#apiKeysTableBody .btn-edit').forEach(btn => {
        btn.addEventListener('click', function() {
            const id = this.getAttribute('data-id');
            editApiKey(id);
        });
    });
    
    document.querySelectorAll('#apiKeysTableBody .btn-delete').forEach(btn => {
        btn.addEventListener('click', function() {
            const id = this.getAttribute('data-id');
            deleteApiKey(id);
        });
    });
    
    document.querySelectorAll('#apiKeysTableBody .btn-enable, #apiKeysTableBody .btn-disable').forEach(btn => {
        btn.addEventListener('click', function() {
            const id = this.getAttribute('data-id');
            toggleApiKeyStatus(id);
        });
    });
}

// 加载社区图片数据
async function loadSharedImages() {
    try {
        const searchTerm = document.getElementById('searchSharedImage')?.value || '';
        const category = document.getElementById('filterImageCategory')?.value || '';
        const user = document.getElementById('filterImageUser')?.value || '';
        
        const queryParams = new URLSearchParams();
        if (searchTerm) queryParams.append('search', searchTerm);
        if (category) queryParams.append('category', category);
        if (user) queryParams.append('user', user);
        queryParams.append('page', currentPage);
        queryParams.append('limit', pageSize);
        
        const data = await fetchAPI(`/api/shared-images?${queryParams.toString()}`);
        
        if (data && !data.error) {
            if (data.success && Array.isArray(data.data)) {
                renderSharedImagesGrid(data.data);
                renderPagination(data.data.length, 'sharedImagesPagination');
            } else {
                renderSharedImagesGrid([]);
                showMessage('未找到社区图片数据', 'warning');
            }
        } else {
            renderSharedImagesGrid([]);
            showMessage(data?.error || '加载社区图片数据失败', 'error');
        }
    } catch (error) {
        console.error('加载社区图片数据异常:', error);
        renderSharedImagesGrid([]);
        showMessage('加载社区图片数据异常', 'error');
    }
}

// 渲染社区图片网格
function renderSharedImagesGrid(images) {
    const grid = document.getElementById('sharedImagesGrid');
    grid.innerHTML = '';
    
    if (images.length === 0) {
        grid.innerHTML = '<div class="no-data">暂无图片数据</div>';
        return;
    }
    
    images.forEach(image => {
        const imageCard = document.createElement('div');
        imageCard.className = 'image-card';
        imageCard.innerHTML = `
            <div class="image-preview">
                <img src="${image.image_path}" alt="${image.title}" loading="lazy">
            </div>
            <div class="image-info">
                <h4 title="${image.title}">${image.title}</h4>
                <p class="image-category">${image.category}</p>
                <p class="image-stats">
                    <span>👁 ${image.view_count || 0}</span>
                    <span>❤ ${image.like_count || 0}</span>
                </p>
                <div class="image-actions">
                    <button class="btn-action btn-view" data-id="${image.id}">查看</button>
                    <button class="btn-action btn-delete" data-id="${image.id}">删除</button>
                </div>
            </div>
        `;
        grid.appendChild(imageCard);
    });
    
    // 添加按钮事件
    document.querySelectorAll('#sharedImagesGrid .btn-view').forEach(btn => {
        btn.addEventListener('click', function() {
            const id = this.getAttribute('data-id');
            viewSharedImage(id);
        });
    });
    
    document.querySelectorAll('#sharedImagesGrid .btn-delete').forEach(btn => {
        btn.addEventListener('click', function() {
            const id = this.getAttribute('data-id');
            deleteSharedImage(id);
        });
    });
}

// 加载文件统计信息
async function loadFileStats() {
    try {
        const data = await fetchAPI('/api/admin/uploads/stats');
        
        if (data && data.success) {
            const stats = data.data;
            document.getElementById('totalFiles').textContent = stats.totalFiles || 0;
            document.getElementById('usedFiles').textContent = stats.usedFiles || 0;
            document.getElementById('unusedFiles').textContent = stats.unusedFiles || 0;
            document.getElementById('totalSize').textContent = stats.totalSizeMB ? `${stats.totalSizeMB} MB` : '0 MB';
        } else {
            showMessage(data?.error || '加载文件统计失败', 'error');
        }
    } catch (error) {
        console.error('加载文件统计异常:', error);
        showMessage('加载文件统计异常', 'error');
    }
}

// 预览文件清理
async function previewCleanup() {
    try {
        const data = await fetchAPI('/api/admin/uploads/cleanup/preview');
        
        if (data && data.success) {
            const results = data.data;
            document.getElementById('unusedFilesList').style.display = 'block';
            document.getElementById('unusedFilesContent').innerHTML = `
                <p>${results.message}</p>
                <ul>
                    ${results.unusedFiles.map(file => `<li>${file}</li>`).join('')}
                </ul>
            `;
            document.getElementById('executeCleanupBtn').disabled = results.unusedFiles.length === 0;
        } else {
            showMessage(data?.error || '预览清理失败', 'error');
        }
    } catch (error) {
        console.error('预览清理异常:', error);
        showMessage('预览清理异常', 'error');
    }
}

// 执行文件清理
async function executeCleanup() {
    if (!confirm('确定要删除这些未使用的文件吗？此操作不可撤销！')) {
        return;
    }
    
    try {
        const data = await fetchAPI('/api/admin/uploads/cleanup', 'POST');
        
        if (data && data.success) {
            const results = data.data;
            document.getElementById('cleanupResults').style.display = 'block';
            document.getElementById('cleanupResultsContent').innerHTML = `
                <p class="success">${results.message}</p>
                <ul>
                    ${results.deletedFiles.map(file => `<li>已删除: ${file}</li>`).join('')}
                </ul>
            `;
            document.getElementById('executeCleanupBtn').disabled = true;
            // 刷新统计信息
            loadFileStats();
            showMessage('文件清理完成', 'success');
        } else {
            showMessage(data?.error || '执行清理失败', 'error');
        }
    } catch (error) {
        console.error('执行清理异常:', error);
        showMessage('执行清理异常', 'error');
    }
}

// 显示接口测试文档
function showApiDocumentation() {
    // 隐藏系统设置视图
    document.getElementById('system-view').style.display = 'none';
    // 显示接口文档视图
    document.getElementById('api-docs-view').style.display = 'block';
    // 更新页面标题
    document.getElementById('pageTitle').textContent = '接口测试文档';
    
    // 加载接口文档内容
    loadApiDocumentation();
}

// 隐藏接口测试文档，返回系统设置
function hideApiDocumentation() {
    // 隐藏接口文档视图
    document.getElementById('api-docs-view').style.display = 'none';
    // 显示系统设置视图
    document.getElementById('system-view').style.display = 'block';
    // 更新页面标题
    document.getElementById('pageTitle').textContent = '系统设置';
}

// 加载接口文档内容
function loadApiDocumentation() {
    const apiDocsContent = `
        <h1>Mars Intelligence 接口测试文档</h1>
        <p>本文档提供了所有API接口的详细测试信息，包括完整URL、请求方式、请求头、请求体示例等。</p>
        
        <h2>基础URL</h2>
        <p>所有接口的基础URL为：<code>http://localhost:3000</code></p>
        
        <h2>1. 用户认证接口</h2>
        
        <h3>1.1 普通用户注册</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/auth/register</code></li>
            <li><strong>请求方式</strong>: <code>POST</code></li>
            <li><strong>请求头</strong>:</li>
        </ul>
        <pre><code>Content-Type: application/json</code></pre>
        <ul>
            <li><strong>请求体示例</strong>:</li>
        </ul>
        <pre><code>{
  "username": "testuser",
  "password": "password123",
  "email": "test@example.com"
}</code></pre>
        <ul>
            <li><strong>测试工具</strong>: Postman, curl, 或其他HTTP客户端</li>
            <li><strong>curl示例</strong>:</li>
        </ul>
        <pre><code>curl -X POST http://localhost:3000/api/auth/register \\
  -H "Content-Type: application/json" \\
  -d '{"username": "testuser", "password": "password123", "email": "test@example.com"}'</code></pre>
        
        <h3>1.2 普通用户登录</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/auth/login</code></li>
            <li><strong>请求方式</strong>: <code>POST</code></li>
            <li><strong>请求头</strong>:</li>
        </ul>
        <pre><code>Content-Type: application/json</code></pre>
        <ul>
            <li><strong>请求体示例</strong>:</li>
        </ul>
        <pre><code>{
  "username": "testuser",
  "password": "password123"
}</code></pre>
        <ul>
            <li><strong>curl示例</strong>:</li>
        </ul>
        <pre><code>curl -X POST http://localhost:3000/api/auth/login \\
  -H "Content-Type: application/json" \\
  -d '{"username": "testuser", "password": "password123"}'</code></pre>
        <p><strong>注意</strong>: 登录成功后会返回JWT令牌，请保存此令牌用于后续需要认证的API请求</p>
        
        <h3>1.3 管理员注册</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/auth/admin/register</code></li>
            <li><strong>请求方式</strong>: <code>POST</code></li>
            <li><strong>请求体示例</strong>:</li>
        </ul>
        <pre><code>{
  "username": "admin",
  "password": "admin123",
  "email": "admin@example.com",
  "adminKey": "admin_secret_key_12345"
}</code></pre>
        <p><strong>注意</strong>: adminKey需要与.env文件中设置的ADMIN_REGISTER_KEY值一致</p>
        
        <h3>1.4 管理员登录</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/auth/admin/login</code></li>
            <li><strong>请求方式</strong>: <code>POST</code></li>
            <li><strong>请求体示例</strong>:</li>
        </ul>
        <pre><code>{
  "username": "admin",
  "password": "admin123"
}</code></pre>
        
        <h2>2. AI角色管理接口</h2>
        
        <h3>2.1 获取所有AI角色</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/airoles</code></li>
            <li><strong>请求方式</strong>: <code>GET</code></li>
            <li><strong>请求头</strong>: 无需特殊请求头</li>
            <li><strong>curl示例</strong>:</li>
        </ul>
        <pre><code>curl -X GET http://localhost:3000/api/airoles</code></pre>
        
        <h3>2.2 获取单个AI角色</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/airoles/{id}</code></li>
            <li><strong>请求方式</strong>: <code>GET</code></li>
            <li><strong>请求参数</strong>: 路径参数 <code>id</code> - AI角色的ID</li>
            <li><strong>curl示例</strong>:</li>
        </ul>
        <pre><code>curl -X GET http://localhost:3000/api/airoles/1</code></pre>
        
        <h3>2.3 创建AI角色（管理员）</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/airoles</code></li>
            <li><strong>请求方式</strong>: <code>POST</code></li>
            <li><strong>请求头</strong>:</li>
        </ul>
        <pre><code>Content-Type: application/json
Authorization: Bearer <您的管理员JWT令牌></code></pre>
        <ul>
            <li><strong>请求体示例</strong>:</li>
        </ul>
        <pre><code>{
  "name": "职场顾问",
  "description": "专注于提供职场建议的AI角色",
  "avatar": "/uploads/career-advisor.png",
  "type": "assistant",
  "api_provider": "openai",
  "api_config": {
    "model": "gpt-3.5-turbo"
  },
  "system_prompt": "你是一个职场顾问，专注于帮助用户解决工作中的问题，提供职业规划建议，并协助处理职场关系。"
}</code></pre>
        <blockquote>
            <p><strong>重要说明</strong>: <code>type</code> 字段只能使用以下枚举值之一:</p>
            <ul>
                <li><code>assistant</code> - 通用助手</li>
                <li><code>tutor</code> - 教育导师</li>
                <li><code>entertainment</code> - 娱乐伙伴</li>
                <li><code>other</code> - 其他类型</li>
            </ul>
        </blockquote>
        <p><strong>注意</strong>: 需要管理员权限才能创建AI角色</p>
        
        <h3>2.4 更新AI角色（管理员）</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/airoles/{id}</code></li>
            <li><strong>请求方式</strong>: <code>PUT</code></li>
            <li><strong>请求头</strong>:</li>
        </ul>
        <pre><code>Content-Type: application/json
Authorization: Bearer <您的管理员JWT令牌></code></pre>
        <p><strong>注意</strong>: 需要管理员权限才能更新AI角色</p>
        
        <h2>3. 交互记录接口</h2>
        
        <h3>3.1 创建交互记录</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/interactions</code></li>
            <li><strong>请求方式</strong>: <code>POST</code></li>
            <li><strong>请求头</strong>:</li>
        </ul>
        <pre><code>Content-Type: application/json
Authorization: Bearer <您的JWT令牌></code></pre>
        <ul>
            <li><strong>请求体示例</strong>:</li>
        </ul>
        <pre><code>{
  "ai_role_id": 1,
  "input": "你好，请介绍一下自己",
  "type": "text"
}</code></pre>
        <ul>
            <li><strong>成功响应示例</strong>:</li>
        </ul>
        <pre><code>{
  "response": "你好！我是智能助手，很高兴为你服务。我可以回答问题、提供信息和建议。有什么我可以帮助你的吗？"
}</code></pre>
        
        <h3>3.2 获取交互历史</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/interactions</code></li>
            <li><strong>请求方式</strong>: <code>GET</code></li>
            <li><strong>请求头</strong>:</li>
        </ul>
        <pre><code>Authorization: Bearer <您的JWT令牌></code></pre>
        
        <h3>3.3 管理员测试接口</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/interactions/test</code></li>
            <li><strong>请求方式</strong>: <code>POST</code></li>
            <li><strong>请求头</strong>:</li>
        </ul>
        <pre><code>Content-Type: application/json
Authorization: Bearer <您的管理员JWT令牌></code></pre>
        <p><strong>注意</strong>: 此接口仅用于管理员测试，不会创建交互记录。需要管理员权限才能访问。</p>
        
        <h2>4. 收藏管理接口</h2>
        
        <h3>4.1 添加收藏</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/favorites</code></li>
            <li><strong>请求方式</strong>: <code>POST</code></li>
            <li><strong>请求体示例</strong>:</li>
        </ul>
        <pre><code>{
  "ai_role_id": 1
}</code></pre>
        
        <h3>4.2 取消收藏</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/favorites/{ai_role_id}</code></li>
            <li><strong>请求方式</strong>: <code>DELETE</code></li>
        </ul>
        
        <h3>4.3 获取用户收藏列表</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/favorites</code></li>
            <li><strong>请求方式</strong>: <code>GET</code></li>
        </ul>
        
        <h3>4.4 检查是否已收藏</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/favorites/check/{ai_role_id}</code></li>
            <li><strong>请求方式</strong>: <code>GET</code></li>
        </ul>
        
        <h2>5. API密钥管理接口</h2>
        
        <h3>5.1 获取API密钥列表（管理员）</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/api-keys</code></li>
            <li><strong>请求方式</strong>: <code>GET</code></li>
            <li><strong>请求头</strong>:</li>
        </ul>
        <pre><code>Authorization: Bearer <您的管理员JWT令牌></code></pre>
        <p><strong>注意</strong>: 需要管理员权限才能访问</p>
        
        <h3>5.2 创建API密钥（管理员）</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/api-keys</code></li>
            <li><strong>请求方式</strong>: <code>POST</code></li>
            <li><strong>请求体示例</strong>:</li>
        </ul>
        <pre><code>{
  "name": "DeepSeek AI服务",
  "provider": "deepseek",
  "api_key": "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "daily_limit": 1000,
  "monthly_limit": 30000,
  "notes": "ET项目DeepSeek AI对话服务",
  "api_config": {
    "model": "deepseek-chat",
    "temperature": 0.7,
    "max_tokens": 800
  }
}</code></pre>
        
        <h3>5.3 更新API密钥（管理员）</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/api-keys/{id}</code></li>
            <li><strong>请求方式</strong>: <code>PUT</code></li>
        </ul>
        
        <h3>5.4 删除API密钥（管理员）</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/api-keys/{id}</code></li>
            <li><strong>请求方式</strong>: <code>DELETE</code></li>
        </ul>
        
        <h3>5.5 测试API密钥（管理员）</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/api-keys/{id}/test</code></li>
            <li><strong>请求方式</strong>: <code>POST</code></li>
        </ul>
        
        <h3>5.6 获取API密钥概览（管理员）</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/api-keys/overview</code></li>
            <li><strong>请求方式</strong>: <code>GET</code></li>
        </ul>
        
        <h3>5.7 获取特定提供商的API密钥（ET客户端）</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/et/keys/{provider}</code></li>
            <li><strong>请求方式</strong>: <code>GET</code></li>
            <li><strong>请求参数</strong>: 路径参数 <code>provider</code> - API提供商名称（如：deepseek, openai, volcengine等）</li>
        </ul>
        
        <h3>5.8 获取所有活跃的API密钥（ET客户端）</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/et/keys/all</code></li>
            <li><strong>请求方式</strong>: <code>GET</code></li>
        </ul>
        
        <h3>5.9 更新API密钥使用统计</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/et/keys/usage</code></li>
            <li><strong>请求方式</strong>: <code>POST</code></li>
            <li><strong>请求体示例</strong>:</li>
        </ul>
        <pre><code>{
  "provider": "deepseek",
  "usage_count": 1,
  "tokens_used": 150
}</code></pre>
        
        <h3>支持的API提供商</h3>
        <ul>
            <li><strong>deepseek</strong> - DeepSeek AI (密钥格式: sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)</li>
            <li><strong>volcengine</strong> - 火山引擎图片生成 (密钥格式: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)</li>
            <li><strong>volcengine_tts</strong> - 火山引擎TTS (密钥格式: Access Token)</li>
            <li><strong>openai</strong> - OpenAI (密钥格式: sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)</li>
            <li><strong>claude</strong> - Anthropic Claude (密钥格式: sk-ant-api03-xxxxxx)</li>
            <li><strong>gemini</strong> - Google Gemini (密钥格式: 长字母数字字符串)</li>
        </ul>
        
        <h2>6. 文件上传接口</h2>
        
        <h3>6.1 上传单个文件</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/upload</code></li>
            <li><strong>请求方式</strong>: <code>POST</code></li>
            <li><strong>请求头</strong>:</li>
        </ul>
        <pre><code>Authorization: Bearer <您的JWT令牌>
Content-Type: multipart/form-data</code></pre>
        <ul>
            <li><strong>请求参数</strong>: <code>file</code> - 要上传的文件</li>
        </ul>
        <p><strong>注意</strong>: 在Postman中，请使用form-data选项并添加一个名为"file"的文件类型字段</p>
        
        <h3>6.2 上传多个文件</h3>
        <ul>
            <li><strong>完整URL</strong>: <code>http://localhost:3000/api/upload/multiple</code></li>
            <li><strong>请求方式</strong>: <code>POST</code></li>
            <li><strong>请求参数</strong>: <code>files</code> - 要上传的文件列表（最多5个）</li>
        </ul>
        
        <h2>测试流程建议</h2>
        <ol>
            <li>首先注册一个普通用户和一个管理员用户</li>
            <li>分别使用普通用户和管理员账号登录并获取JWT令牌</li>
            <li>使用管理员JWT令牌测试需要管理员权限的接口（如创建AI角色）</li>
            <li>使用普通用户JWT令牌测试普通功能</li>
            <li>按照以下顺序测试功能:
                <ul>
                    <li>获取AI角色列表</li>
                    <li>创建交互记录</li>
                    <li>获取交互历史</li>
                    <li>管理员测试接口（仅管理员）</li>
                    <li>添加收藏</li>
                    <li>获取收藏列表</li>
                    <li>检查收藏状态</li>
                    <li>API密钥管理（仅管理员）</li>
                    <li>ET客户端获取密钥</li>
                    <li>上传文件</li>
                    <li>取消收藏</li>
                </ul>
            </li>
        </ol>
        
        <h2>常见问题排查</h2>
        <ol>
            <li>如果遇到401错误，请检查JWT令牌是否正确或是否已过期</li>
            <li>如果遇到403错误，请检查用户权限是否足够（普通用户尝试访问管理员接口会返回此错误）</li>
            <li>如果遇到404错误，请检查请求的资源ID是否存在</li>
            <li>如果遇到500错误，请检查服务器日志以获取更多信息</li>
            <li>如果在创建或更新AI角色时出现 "Data truncated for column 'type'" 错误，请确保 <code>type</code> 字段值只使用允许的枚举值: <code>assistant</code>, <code>tutor</code>, <code>entertainment</code> 或 <code>other</code></li>
        </ol>
    `;
    
    document.getElementById('apiDocsContent').innerHTML = apiDocsContent;
}

// 加载系统设置
async function loadSystemSettings() {
    // 系统设置暂时使用本地存储模拟
    const adminRegisterKey = localStorage.getItem('adminRegisterKey') || '';
    const maxUploadSize = localStorage.getItem('maxUploadSize') || '10';
    
    document.getElementById('adminRegisterKey').value = adminRegisterKey;
    document.getElementById('maxUploadSize').value = maxUploadSize;
    
    // 添加表单提交事件
    const form = document.getElementById('systemConfigForm');
    if (form && !form.hasAttribute('data-initialized')) {
        form.setAttribute('data-initialized', 'true');
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const adminRegisterKey = document.getElementById('adminRegisterKey').value;
            const maxUploadSize = document.getElementById('maxUploadSize').value;
            
            // 保存到本地存储
            localStorage.setItem('adminRegisterKey', adminRegisterKey);
            localStorage.setItem('maxUploadSize', maxUploadSize);
            
            showMessage('系统设置已保存', 'success');
        });
    }
    
    // 初始化数据导出功能
    initializeDataExport();
}

// 初始化数据导出功能
function initializeDataExport() {
    const exportDataBtn = document.getElementById('exportDataBtn');
    const exportSchemaBtn = document.getElementById('exportSchemaBtn');
    
    if (exportDataBtn && !exportDataBtn.hasAttribute('data-initialized')) {
        exportDataBtn.setAttribute('data-initialized', 'true');
        exportDataBtn.addEventListener('click', exportData);
    }
    
    if (exportSchemaBtn && !exportSchemaBtn.hasAttribute('data-initialized')) {
        exportSchemaBtn.setAttribute('data-initialized', 'true');
        exportSchemaBtn.addEventListener('click', exportSchema);
    }
}

// 导出数据功能
async function exportData() {
    const selectedTables = getSelectedTables();
    const format = document.getElementById('exportFormat').value;
    
    if (selectedTables.length === 0) {
        showMessage('请至少选择一个数据表', 'warning');
        return;
    }
    
    showExportStatus(true);
    
    try {
        const response = await fetchAPI('/api/admin/export-data', 'POST', {
            tables: selectedTables,
            format: format
        });
        
        if (response.success) {
            downloadFile(response.data, `database_export_${new Date().toISOString().split('T')[0]}.${format}`);
            showMessage('数据导出成功', 'success');
        } else {
            showMessage(response.error || '数据导出失败', 'error');
        }
    } catch (error) {
        console.error('导出数据异常:', error);
        showMessage('导出数据异常', 'error');
    } finally {
        showExportStatus(false);
    }
}

// 导出表结构功能
async function exportSchema() {
    const selectedTables = getSelectedTables();
    
    if (selectedTables.length === 0) {
        showMessage('请至少选择一个数据表', 'warning');
        return;
    }
    
    showExportStatus(true);
    
    try {
        const response = await fetchAPI('/api/admin/export-schema', 'POST', {
            tables: selectedTables
        });
        
        if (response.success) {
            downloadFile(response.data, `database_schema_${new Date().toISOString().split('T')[0]}.sql`);
            showMessage('表结构导出成功', 'success');
        } else {
            showMessage(response.error || '表结构导出失败', 'error');
        }
    } catch (error) {
        console.error('导出表结构异常:', error);
        showMessage('导出表结构异常', 'error');
    } finally {
        showExportStatus(false);
    }
}

// 获取选中的数据表
function getSelectedTables() {
    const tables = [];
    const checkboxes = [
        { id: 'exportUsers', table: 'Users' },
        { id: 'exportAiRoles', table: 'AIRoles' },
        { id: 'exportApiKeys', table: 'ApiKeys' },
        { id: 'exportSharedImages', table: 'SharedImages' },
        { id: 'exportInteractions', table: 'Interactions' },
        { id: 'exportUserLikes', table: 'UserLikes' }
    ];
    
    checkboxes.forEach(checkbox => {
        const element = document.getElementById(checkbox.id);
        if (element && element.checked) {
            tables.push(checkbox.table);
        }
    });
    
    return tables;
}

// 显示/隐藏导出状态
function showExportStatus(show) {
    const statusElement = document.getElementById('exportStatus');
    if (statusElement) {
        statusElement.style.display = show ? 'block' : 'none';
    }
}

// 下载文件
function downloadFile(content, filename) {
    const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
}

// 渲染分页控件
function renderPagination(totalItems, paginationId) {
    totalPages = Math.ceil(totalItems / pageSize);
    const pagination = document.getElementById(paginationId);
    pagination.innerHTML = '';
    
    if (totalPages <= 1) return;
    
    // 上一页按钮
    const prevBtn = document.createElement('button');
    prevBtn.classList.add('pagination-btn');
    prevBtn.disabled = currentPage === 1;
    prevBtn.textContent = '上一页';
    prevBtn.addEventListener('click', function() {
        if (currentPage > 1) {
            currentPage--;
            if (currentView === 'ai-roles') {
                loadAiRoles();
            }
        }
    });
    pagination.appendChild(prevBtn);
    
    // 页码按钮
    for (let i = 1; i <= totalPages; i++) {
        const pageBtn = document.createElement('button');
        pageBtn.classList.add('pagination-btn');
        if (i === currentPage) pageBtn.classList.add('active');
        pageBtn.textContent = i;
        pageBtn.addEventListener('click', function() {
            currentPage = i;
            if (currentView === 'ai-roles') {
                loadAiRoles();
            }
        });
        pagination.appendChild(pageBtn);
    }
    
    // 下一页按钮
    const nextBtn = document.createElement('button');
    nextBtn.classList.add('pagination-btn');
    nextBtn.disabled = currentPage === totalPages;
    nextBtn.textContent = '下一页';
    nextBtn.addEventListener('click', function() {
        if (currentPage < totalPages) {
            currentPage++;
            if (currentView === 'ai-roles') {
                loadAiRoles();
            }
        }
    });
    pagination.appendChild(nextBtn);
}

// 显示创建AI角色模态框
function showCreateAiRoleModal() {
    // 重置表单
    document.getElementById('aiRoleForm').reset();
    document.getElementById('aiRoleId').value = '';
    document.getElementById('modalTitle').textContent = '创建新AI角色';
    
    // 重置头像上传组件
    resetAvatarUpload();
    
    // 显示模态框
    document.getElementById('aiRoleModal').style.display = 'flex';
    
    // 绑定API提供商建议按钮事件
    setupApiProviderSuggestions();
    
    // 绑定头像上传事件
    setupAvatarUpload();
}

// 查看AI角色
async function viewAiRole(id) {
    const role = await fetchAPI(`/api/airoles/${id}`);
    
    if (role && !role.error) {
        // 填充角色详情信息
        document.getElementById('viewModalTitle').textContent = `角色详情: ${role.name}`;
        document.getElementById('viewName').textContent = role.name;
        
        // 设置角色类型（使用友好显示名称）
        const typeMap = {
            'assistant': '通用助手',
            'tutor': '教育导师',
            'entertainment': '娱乐伙伴',
            'other': '其他类型'
        };
        document.getElementById('viewType').textContent = typeMap[role.type] || role.type;
        
        // 提取并显示模型信息
        let modelName = '未设置';
        try {
            if (role.api_config && typeof role.api_config === 'object') {
                modelName = role.api_config.model || '未设置';
            } else if (typeof role.api_config === 'string') {
                // 如果存储为字符串，尝试解析
                const configObj = JSON.parse(role.api_config);
                modelName = configObj.model || '未设置';
            }
        } catch (e) {
            console.warn('无法解析API配置', e);
        }
        document.getElementById('viewModel').textContent = modelName;
        
        // 设置其他信息
        document.getElementById('viewProvider').textContent = role.api_provider;
        document.getElementById('viewDescription').textContent = role.description || '无描述';
        document.getElementById('viewSystemPrompt').textContent = role.system_prompt || '无系统提示词';
        document.getElementById('viewApiConfig').textContent = JSON.stringify(role.api_config || {}, null, 2);
        document.getElementById('viewCreatedAt').textContent = new Date(role.created_at).toLocaleString();
        
        // 设置头像
        const defaultAvatar = `data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="36" height="36"><circle cx="12" cy="7" r="5" fill="%23718096"/><path d="M21,24v-5c0-4.4-3.6-8-8-8h-2c-4.4,0-8,3.6-8,8v5" fill="%23718096"/></svg>`;
        const avatarEl = document.getElementById('viewAvatar');
        avatarEl.src = role.avatar || defaultAvatar;
        avatarEl.onerror = function() {
            this.onerror = null;
            this.src = defaultAvatar;
        };
        
        // 测试功能已移除
        
        // 显示模态框
        document.getElementById('aiRoleViewModal').style.display = 'flex';
        
        // 关闭按钮绑定事件
        document.querySelectorAll('#aiRoleViewModal .close-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                document.getElementById('aiRoleViewModal').style.display = 'none';
            });
        });
    } else {
        showError(role.error || '获取AI角色数据失败');
    }
}

// 测试调用AI角色功能已移除

// 编辑AI角色
async function editAiRole(id) {
    const role = await fetchAPI(`/api/airoles/${id}`);
    
    if (role && !role.error) {
        // 填充表单
        document.getElementById('aiRoleId').value = role.id;
        document.getElementById('name').value = role.name;
        document.getElementById('description').value = role.description;
        document.getElementById('type').value = role.type;
        document.getElementById('apiProvider').value = role.api_provider;
        document.getElementById('apiConfig').value = JSON.stringify(role.api_config, null, 2);
        document.getElementById('systemPrompt').value = role.system_prompt;
        document.getElementById('avatar').value = role.avatar;
        
        // 设置头像预览
        if (role.avatar) {
            const avatarPreviewImg = document.getElementById('avatarPreviewImg');
            const uploadPlaceholder = document.getElementById('uploadPlaceholder');
            const removeAvatarBtn = document.getElementById('removeAvatarBtn');
            
            const avatarUrl = role.avatar.startsWith('http') ? role.avatar : `${window.location.origin}${role.avatar}`;
            avatarPreviewImg.src = avatarUrl;
            avatarPreviewImg.style.display = 'block';
            uploadPlaceholder.style.display = 'none';
            removeAvatarBtn.style.display = 'inline-block';
        } else {
            resetAvatarUpload();
        }
        
        // 更新标题
        document.getElementById('modalTitle').textContent = '编辑AI角色';
        
        // 显示模态框
        document.getElementById('aiRoleModal').style.display = 'flex';
        
        // 绑定API提供商建议按钮事件
        setupApiProviderSuggestions();
        
        // 绑定头像上传事件
        setupAvatarUpload();
    } else {
        showError(role.error || '获取AI角色数据失败');
    }
}

// 设置API提供商建议按钮
function setupApiProviderSuggestions() {
    document.querySelectorAll('.suggestion-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const value = this.getAttribute('data-value');
            document.getElementById('apiProvider').value = value;
            
            // 如果是自定义，可以清空输入框让用户填写
            if (value === 'Custom') {
                document.getElementById('apiProvider').value = '';
                document.getElementById('apiProvider').focus();
            }
            
            // 根据所选的API提供商提供适当的配置模板
            let configTemplate = {};
            switch(value) {
                case 'OpenAI':
                    configTemplate = {
                        model: "gpt-3.5-turbo",
                        temperature: 0.7,
                        max_tokens: 800
                    };
                    break;
                case 'Volcengine':
                case 'doubao':
                    configTemplate = {
                        model: "doubao-pro-32k",
                        temperature: 0.7,
                        max_tokens: 800,
                        endpoint: "https://ark.cn-beijing.volces.com/api/v3/chat/completions"
                    };
                    break;
                case 'Azure':
                    configTemplate = {
                        deployment_id: "YOUR_DEPLOYMENT_ID",
                        api_version: "2023-05-15",
                        endpoint: "YOUR_AZURE_ENDPOINT"
                    };
                    break;
                case 'Anthropic':
                    configTemplate = {
                        model: "claude-2",
                        temperature: 0.7,
                        max_tokens: 1000
                    };
                    break;
                case 'Gemini':
                    configTemplate = {
                        model: "gemini-pro",
                        temperature: 0.7,
                        max_output_tokens: 800
                    };
                    break;
                case 'deepseek':
                    configTemplate = {
                        model: "deepseek-chat",
                        temperature: 0.7,
                        max_tokens: 800,
                        stream: false
                    };
                    break;
            }
            
            // 如果不是自定义且有配置模板，则更新配置
            if (value !== 'Custom' && Object.keys(configTemplate).length > 0) {
                document.getElementById('apiConfig').value = JSON.stringify(configTemplate, null, 2);
            }
        });
    });
}

// 设置头像上传功能
function setupAvatarUpload() {
    const avatarFile = document.getElementById('avatarFile');
    const selectAvatarBtn = document.getElementById('selectAvatarBtn');
    const removeAvatarBtn = document.getElementById('removeAvatarBtn');
    const avatarPreview = document.getElementById('avatarPreview');
    const avatarPreviewImg = document.getElementById('avatarPreviewImg');
    const uploadPlaceholder = document.getElementById('uploadPlaceholder');
    const avatarInput = document.getElementById('avatar');
    
    // 点击选择文件按钮
    selectAvatarBtn.addEventListener('click', () => {
        avatarFile.click();
    });
    
    // 点击预览区域也可以选择文件
    avatarPreview.addEventListener('click', () => {
        avatarFile.click();
    });
    
    // 文件选择变化事件
    avatarFile.addEventListener('change', async (e) => {
        const file = e.target.files[0];
        if (file) {
            // 验证文件类型
            if (!file.type.startsWith('image/')) {
                showError('请选择图片文件');
                return;
            }
            
            // 验证文件大小 (5MB)
            if (file.size > 5 * 1024 * 1024) {
                showError('图片文件大小不能超过5MB');
                return;
            }
            
            // 显示上传进度
            const uploadPlaceholder = document.getElementById('uploadPlaceholder');
            uploadPlaceholder.innerHTML = '<span style="color: #1890ff;">正在上传...</span>';
            
            // 显示预览
            const reader = new FileReader();
            reader.onload = (e) => {
                avatarPreviewImg.src = e.target.result;
                avatarPreviewImg.style.display = 'block';
                uploadPlaceholder.style.display = 'none';
                removeAvatarBtn.style.display = 'inline-block';
            };
            reader.readAsDataURL(file);
            
            try {
                // 上传文件
                await uploadAvatarFile(file);
            } catch (error) {
                // 上传失败时恢复占位符
                uploadPlaceholder.innerHTML = '<span>点击上传头像</span>';
                uploadPlaceholder.style.display = 'block';
                avatarPreviewImg.style.display = 'none';
                removeAvatarBtn.style.display = 'none';
            }
        }
    });
    
    // 移除头像
    removeAvatarBtn.addEventListener('click', () => {
        resetAvatarUpload();
    });
}

// 上传头像文件
async function uploadAvatarFile(file, retryCount = 0) {
    try {
        const formData = new FormData();
        formData.append('file', file);
        
        console.log('开始上传头像文件:', file.name, '大小:', file.size);
        
        const response = await fetch('/api/upload', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
            },
            body: formData
        });
        
        const result = await response.json();
        
        if (response.ok && result.url) {
            console.log('头像上传成功:', result.url);
            // 设置头像URL到隐藏输入框
            document.getElementById('avatar').value = result.url;
            showSuccess('头像上传成功');
            return result.url;
        } else {
            throw new Error(result.error || '上传失败');
        }
    } catch (error) {
        console.error('头像上传失败:', error);
        
        // 如果是网络错误且重试次数少于3次，则重试
        if (retryCount < 3 && (error.name === 'TypeError' || error.message.includes('fetch'))) {
            console.log(`头像上传重试 ${retryCount + 1}/3`);
            await new Promise(resolve => setTimeout(resolve, 1000 * (retryCount + 1))); // 递增延迟
            return uploadAvatarFile(file, retryCount + 1);
        }
        
        showError('头像上传失败: ' + error.message);
        resetAvatarUpload();
        throw error;
    }
}

// 重置头像上传组件
function resetAvatarUpload() {
    const avatarFile = document.getElementById('avatarFile');
    const avatarPreviewImg = document.getElementById('avatarPreviewImg');
    const uploadPlaceholder = document.getElementById('uploadPlaceholder');
    const removeAvatarBtn = document.getElementById('removeAvatarBtn');
    const avatarInput = document.getElementById('avatar');
    
    if (avatarFile) avatarFile.value = '';
    if (avatarPreviewImg) {
        avatarPreviewImg.src = '';
        avatarPreviewImg.style.display = 'none';
    }
    if (uploadPlaceholder) uploadPlaceholder.style.display = 'block';
    if (removeAvatarBtn) removeAvatarBtn.style.display = 'none';
    if (avatarInput) avatarInput.value = '';
}

// 设置用户头像上传功能
function setupUserAvatarUpload() {
    const userAvatarFile = document.getElementById('userAvatarFile');
    const selectUserAvatarBtn = document.getElementById('selectUserAvatarBtn');
    const removeUserAvatarBtn = document.getElementById('removeUserAvatarBtn');
    const userAvatarPreview = document.getElementById('userAvatarPreview');
    const userAvatarPreviewImg = document.getElementById('userAvatarPreviewImg');
    const userUploadPlaceholder = document.getElementById('userUploadPlaceholder');
    const userAvatarInput = document.getElementById('userAvatar');
    
    if (!userAvatarFile || !selectUserAvatarBtn || !userAvatarPreview) {
        return; // 如果元素不存在，直接返回
    }
    
    // 点击选择文件按钮
    selectUserAvatarBtn.addEventListener('click', () => {
        userAvatarFile.click();
    });
    
    // 点击预览区域也可以选择文件
    userAvatarPreview.addEventListener('click', () => {
        userAvatarFile.click();
    });
    
    // 文件选择变化事件
    userAvatarFile.addEventListener('change', async (e) => {
        const file = e.target.files[0];
        if (file) {
            // 验证文件类型
            if (!file.type.startsWith('image/')) {
                showError('请选择图片文件');
                return;
            }
            
            // 验证文件大小 (5MB)
            if (file.size > 5 * 1024 * 1024) {
                showError('图片文件大小不能超过5MB');
                return;
            }
            
            // 显示上传进度
            const userUploadPlaceholder = document.getElementById('userUploadPlaceholder');
            userUploadPlaceholder.innerHTML = '<span style="color: #1890ff;">正在上传...</span>';
            
            // 显示预览
            const reader = new FileReader();
            reader.onload = (e) => {
                if (userAvatarPreviewImg && userUploadPlaceholder && removeUserAvatarBtn) {
                    userAvatarPreviewImg.src = e.target.result;
                    userAvatarPreviewImg.style.display = 'block';
                    userUploadPlaceholder.style.display = 'none';
                    removeUserAvatarBtn.style.display = 'inline-block';
                }
            };
            reader.readAsDataURL(file);
            
            try {
                // 上传文件
                await uploadUserAvatarFile(file);
            } catch (error) {
                // 上传失败时恢复占位符
                if (userUploadPlaceholder && userAvatarPreviewImg && removeUserAvatarBtn) {
                    userUploadPlaceholder.innerHTML = '<span>点击上传头像</span>';
                    userUploadPlaceholder.style.display = 'block';
                    userAvatarPreviewImg.style.display = 'none';
                    removeUserAvatarBtn.style.display = 'none';
                }
            }
        }
    });
    
    // 移除头像
    if (removeUserAvatarBtn) {
        removeUserAvatarBtn.addEventListener('click', () => {
            resetUserAvatarUpload();
        });
    }
}

// 上传用户头像文件
async function uploadUserAvatarFile(file, retryCount = 0) {
    try {
        const formData = new FormData();
        formData.append('file', file);
        
        console.log('开始上传用户头像文件:', file.name, '大小:', file.size);
        
        const response = await fetch('/api/upload', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
            },
            body: formData
        });
        
        const result = await response.json();
        
        if (response.ok && result.url) {
            console.log('用户头像上传成功:', result.url);
            // 设置头像URL到隐藏输入框
            document.getElementById('userAvatar').value = result.url;
            showSuccess('头像上传成功');
            return result.url;
        } else {
            throw new Error(result.error || '上传失败');
        }
    } catch (error) {
        console.error('用户头像上传失败:', error);
        
        // 如果是网络错误且重试次数少于3次，则重试
        if (retryCount < 3 && (error.name === 'TypeError' || error.message.includes('fetch'))) {
            console.log(`用户头像上传重试 ${retryCount + 1}/3`);
            await new Promise(resolve => setTimeout(resolve, 1000 * (retryCount + 1))); // 递增延迟
            return uploadUserAvatarFile(file, retryCount + 1);
        }
        
        showError('头像上传失败: ' + error.message);
        resetUserAvatarUpload();
        throw error;
    }
}

// 重置用户头像上传组件
function resetUserAvatarUpload() {
    const userAvatarFile = document.getElementById('userAvatarFile');
    const userAvatarPreviewImg = document.getElementById('userAvatarPreviewImg');
    const userUploadPlaceholder = document.getElementById('userUploadPlaceholder');
    const removeUserAvatarBtn = document.getElementById('removeUserAvatarBtn');
    const userAvatarInput = document.getElementById('userAvatar');
    
    if (userAvatarFile) userAvatarFile.value = '';
    if (userAvatarPreviewImg) {
        userAvatarPreviewImg.src = '';
        userAvatarPreviewImg.style.display = 'none';
    }
    if (userUploadPlaceholder) userUploadPlaceholder.style.display = 'block';
    if (removeUserAvatarBtn) removeUserAvatarBtn.style.display = 'none';
    if (userAvatarInput) userAvatarInput.value = '';
}

// 删除AI角色
async function deleteAiRole(id) {
    if (confirm('确定要删除这个AI角色吗？此操作不可恢复。')) {
        try {
            console.log(`正在发送删除请求，AI角色ID: ${id}`);
            const result = await fetchAPI(`/api/airoles/${id}`, 'DELETE');
            
            if (result && result.success) {
                showMessage(`删除成功: ${result.message || ''}（ID: ${id}）`);
                // 重新加载AI角色列表
                loadAiRoles();
            } else {
                // 处理可能的错误响应
                const errorMsg = result.error || '删除失败，请稍后重试';
                const detailMsg = result.message ? `(${result.message})` : '';
                showError(`${errorMsg} ${detailMsg}`);
                console.error('删除失败详情:', result);
            }
        } catch (error) {
            // 处理网络或其他异常
            showError(`删除请求失败: ${error.message || '未知错误'}`);
            console.error('删除请求异常:', error);
        }
    }
}

// 处理AI角色表单提交
async function handleAiRoleSubmit(e) {
    e.preventDefault();
    
    const id = document.getElementById('aiRoleId').value;
    const formData = {
        name: document.getElementById('name').value,
        description: document.getElementById('description').value,
        type: document.getElementById('type').value,
        api_provider: document.getElementById('apiProvider').value,
        avatar: document.getElementById('avatar').value,
        system_prompt: document.getElementById('systemPrompt').value
    };
    
    // 解析API配置
    try {
        formData.api_config = JSON.parse(document.getElementById('apiConfig').value);
    } catch (error) {
        showError('API配置JSON格式不正确');
        return;
    }
    
    let result;
    
    if (id) {
        // 更新
        result = await fetchAPI(`/api/airoles/${id}`, 'PUT', formData);
    } else {
        // 创建
        result = await fetchAPI('/api/airoles', 'POST', formData);
    }
    
    if (result && !result.error) {
        showMessage(id ? 'AI角色已更新' : 'AI角色已创建');
        document.getElementById('aiRoleModal').style.display = 'none';
        loadAiRoles();
    } else {
        showError(result.error || (id ? '更新AI角色失败' : '创建AI角色失败'));
    }
}

// 显示消息提示
function showMessage(message) {
    // TODO: 实现消息提示，可以使用弹窗或Toast
    alert(message);
}

// 显示错误提示
function showError(error) {
    // TODO: 实现错误提示，可以使用弹窗或Toast
    alert(`错误: ${error}`);
}

// API密钥管理相关函数

// 加载API密钥列表
async function loadApiKeys() {
    console.log('开始加载API密钥列表');
    const result = await fetchAPI('/api/api-keys');
    
    const tbody = document.getElementById('apiKeysTableBody');
    
    if (result && result.success && result.data) {
        if (result.data.length === 0) {
            tbody.innerHTML = '<tr><td colspan="8" style="text-align: center;">暂无API密钥</td></tr>';
        } else {
            tbody.innerHTML = result.data.map(key => {
                const statusText = key.is_active ? '启用' : '禁用';
                const statusClass = key.is_active ? 'status-active' : 'status-inactive';
                const lastUsed = key.last_used_at ? new Date(key.last_used_at).toLocaleString() : '从未使用';
                const createdAt = new Date(key.created_at).toLocaleString();
                
                return `
                    <tr>
                        <td>${key.id}</td>
                        <td>${key.name}</td>
                        <td>${key.provider}</td>
                        <td><span class="status ${statusClass}">${statusText}</span></td>
                        <td>${key.usage_count || 0}</td>
                        <td>${lastUsed}</td>
                        <td>${createdAt}</td>
                        <td>
                            <button onclick="editApiKey(${key.id})" class="btn-edit">编辑</button>
                            <button onclick="deleteApiKey(${key.id})" class="btn-delete">删除</button>
                        </td>
                    </tr>
                `;
            }).join('');
        }
    } else {
        tbody.innerHTML = `<tr><td colspan="8" style="text-align: center; color: red;">加载失败: ${result?.error || '未知错误'}</td></tr>`;
        console.error('加载API密钥失败:', result);
    }
}

// 显示创建API密钥模态框
function showCreateApiKeyModal() {
    // 重置表单
    document.getElementById('apiKeyForm').reset();
    document.getElementById('apiKeyId').value = '';
    document.getElementById('apiKeyModalTitle').textContent = '创建新API密钥';
    document.getElementById('apiKeyIsActive').checked = true;
    
    // 恢复密钥字段的required属性和占位符
    document.getElementById('apiKeyValue').setAttribute('required', 'required');
    document.getElementById('apiKeyValue').placeholder = '请输入API密钥';
    
    // 显示模态框
    document.getElementById('apiKeyModal').style.display = 'flex';
}

// 处理API密钥表单提交
async function handleApiKeySubmit(e) {
    e.preventDefault();
    
    const formData = new FormData(e.target);
    const apiKeyId = document.getElementById('apiKeyId').value;
    const isEdit = !!apiKeyId;
    const apiKeyValue = formData.get('api_key');
    
    // 验证：创建时必须提供密钥，编辑时可选
    if (!isEdit && (!apiKeyValue || apiKeyValue.trim() === '')) {
        showError('创建新API密钥时必须提供密钥');
        return;
    }
    
    const data = {
        name: formData.get('name'),
        provider: formData.get('provider'),
        is_active: document.getElementById('apiKeyIsActive').checked,
        notes: formData.get('notes') || null
    };
    
    // 只有在密钥不为空时才包含api_key字段
    if (apiKeyValue && apiKeyValue.trim() !== '') {
        data.api_key = apiKeyValue;
    }
    
    // 处理数字字段
    const dailyLimit = formData.get('daily_limit');
    const monthlyLimit = formData.get('monthly_limit');
    if (dailyLimit) data.daily_limit = parseInt(dailyLimit);
    if (monthlyLimit) data.monthly_limit = parseInt(monthlyLimit);
    
    console.log('提交API密钥数据:', { ...data, api_key: '[HIDDEN]' });
    
    const url = isEdit ? `/api/api-keys/${apiKeyId}` : '/api/api-keys';
    const method = isEdit ? 'PUT' : 'POST';
    
    const result = await fetchAPI(url, method, data);
    
    if (result && result.success) {
        showSuccess(isEdit ? 'API密钥更新成功' : 'API密钥创建成功');
        document.getElementById('apiKeyModal').style.display = 'none';
        loadApiKeys(); // 重新加载列表
    } else {
        showError(result?.error || (isEdit ? 'API密钥更新失败' : 'API密钥创建失败'));
    }
}

// 编辑API密钥
async function editApiKey(id) {
    const result = await fetchAPI(`/api/api-keys/${id}`);
    
    if (result && result.success && result.data) {
        const key = result.data;
        
        // 填充表单
        document.getElementById('apiKeyId').value = key.id;
        document.getElementById('apiKeyName').value = key.name;
        document.getElementById('apiKeyProvider').value = key.provider;
        document.getElementById('apiKeyValue').value = ''; // 不显示现有密钥
        document.getElementById('apiKeyValue').placeholder = '留空则保持原密钥不变，输入新密钥则更新';
        document.getElementById('apiKeyValue').removeAttribute('required'); // 编辑时不强制要求
        document.getElementById('apiKeyDailyLimit').value = key.daily_limit || '';
        document.getElementById('apiKeyMonthlyLimit').value = key.monthly_limit || '';
        document.getElementById('apiKeyNotes').value = key.notes || '';
        document.getElementById('apiKeyIsActive').checked = key.is_active;
        
        // 更新标题
        document.getElementById('apiKeyModalTitle').textContent = '编辑API密钥';
        
        // 显示模态框
        document.getElementById('apiKeyModal').style.display = 'flex';
    } else {
        showError(result?.error || '获取API密钥信息失败');
    }
}

// API密钥测试功能已移除

// 删除API密钥
async function deleteApiKey(id) {
    if (!confirm('确定要删除此API密钥吗？此操作不可撤销！')) return;
    
    const result = await fetchAPI(`/api/api-keys/${id}`, 'DELETE');
    
    if (result && result.success) {
        showSuccess('API密钥删除成功');
        loadApiKeys(); // 重新加载列表
    } else {
        showError(result?.error || 'API密钥删除失败');
    }
}

// 社区图片管理相关函数

// 加载社区图片列表
async function loadSharedImages() {
    console.log('开始加载社区图片列表');
    const result = await fetchAPI('/api/shared-images?page=1&limit=20');
    
    const container = document.getElementById('sharedImagesGrid');
    
    if (result && result.success && result.data) {
        if (result.data.images.length === 0) {
            container.innerHTML = '<div class="no-data">暂无社区图片</div>';
        } else {
            container.innerHTML = result.data.images.map(image => {
                const imageUrl = image.image_url && image.image_url.startsWith('http') ? image.image_url : `${window.location.origin}${image.image_path || image.image_url || '/uploads/default-image.png'}`;
                const userName = image.User ? image.User.username : '未知用户';
                const aiRoleName = image.AIRole ? image.AIRole.name : '未知角色';
                
                return `
                    <div class="image-card" onclick="viewSharedImage(${image.id})">
                        <div class="image-thumbnail">
                            <img src="${imageUrl}" alt="${image.title}" onerror="this.src=''">
                        </div>
                        <div class="image-info">
                            <h4>${image.title}</h4>
                            <p class="image-category">${image.category}</p>
                            <div class="image-meta">
                                <span class="user">👤 ${userName}</span>
                                <span class="ai-role">🤖 ${aiRoleName}</span>
                                <span class="likes">❤️ ${image.like_count || 0}</span>
                            </div>
                            <div class="image-actions">
                                <button onclick="event.stopPropagation(); deleteSharedImage(${image.id})" class="btn-delete-small">删除</button>
                            </div>
                        </div>
                    </div>
                `;
            }).join('');
        }
    } else {
        container.innerHTML = `<div class="error-message">加载失败: ${result?.error || '未知错误'}</div>`;
        console.error('加载社区图片失败:', result);
    }
}

// 查看社区图片详情
async function viewSharedImage(id) {
    const result = await fetchAPI(`/api/shared-images/${id}`);
    
    if (result && result.success && result.data) {
        const image = result.data;
        const imageUrl = image.image_url && image.image_url.startsWith('http') ? image.image_url : `${window.location.origin}${image.image_path || image.image_url}`;
        
        // 填充模态框内容
        document.getElementById('sharedImagePreview').src = imageUrl;
        document.getElementById('sharedImageTitle').textContent = image.title;
        document.getElementById('sharedImageDescription').textContent = image.description || '无描述';
        document.getElementById('sharedImageCategory').textContent = image.category;
        document.getElementById('sharedImageUser').textContent = image.User ? image.User.username : '未知用户';
        document.getElementById('sharedImageAiRole').textContent = image.AIRole ? image.AIRole.name : '未知角色';
        document.getElementById('sharedImageLikes').textContent = image.like_count || 0;
        document.getElementById('sharedImageCreatedAt').textContent = new Date(image.created_at).toLocaleString();
        
        // 处理标签
        const tagsContainer = document.getElementById('sharedImageTags');
        if (image.tags) {
            try {
                const tags = typeof image.tags === 'string' ? JSON.parse(image.tags) : image.tags;
                tagsContainer.innerHTML = tags.map(tag => `<span class="tag">${tag}</span>`).join('');
            } catch (e) {
                tagsContainer.innerHTML = '<span class="tag">无标签</span>';
            }
        } else {
            tagsContainer.innerHTML = '<span class="tag">无标签</span>';
        }
        
        // 设置删除按钮
        document.getElementById('deleteSharedImageBtn').onclick = function() {
            deleteSharedImage(image.id);
            document.getElementById('sharedImageModal').style.display = 'none';
        };
        
        // 显示模态框
        document.getElementById('sharedImageModal').style.display = 'flex';
    } else {
        showError(result?.error || '获取图片详情失败');
    }
}

// 删除社区图片
async function deleteSharedImage(id) {
    if (!confirm('确定要删除此图片吗？此操作不可撤销！')) return;
    
    const result = await fetchAPI(`/api/shared-images/${id}`, 'DELETE');
    
    if (result && result.success) {
        showSuccess('图片删除成功');
        loadSharedImages(); // 重新加载列表
    } else {
        showError(result?.error || '图片删除失败');
    }
}

// 显示成功消息
function showSuccess(message) {
    // TODO: 实现成功消息提示，可以使用弹窗或Toast
    alert(message);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 检查当前页面
    const isLoginPage = window.location.href.includes('login.html');
    
    if (!isLoginPage) {
        initDashboard();
    }
    
    // 搜索和筛选事件绑定
    const searchInputs = document.querySelectorAll('.search-input');
    searchInputs.forEach(input => {
        input.addEventListener('input', debounce(function() {
            currentPage = 1;
            if (currentView === 'ai-roles') {
                loadAiRoles();
            }
        }, 500));
    });
    
    const filterSelects = document.querySelectorAll('.filter-select');
    filterSelects.forEach(select => {
        select.addEventListener('change', function() {
            currentPage = 1;
            if (currentView === 'ai-roles') {
                loadAiRoles();
            }
        });
    });
});

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(() => {
            func.apply(context, args);
        }, wait);
    };
}

// ==================== 文件管理相关函数 ====================

// 加载文件统计信息
async function loadFileStats() {
    try {
        const token = getAuthToken();
        const response = await fetch('/api/admin/uploads/stats', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (response.ok) {
            const result = await response.json();
            if (result.success && result.data) {
                updateFileStatsDisplay(result.data);
            } else {
                throw new Error(result.error || '获取文件统计失败');
            }
        } else {
            throw new Error('获取文件统计失败');
        }
    } catch (error) {
        console.error('加载文件统计失败:', error);
        showMessage('加载文件统计失败: ' + error.message, 'error');
    }
}

// 更新文件统计显示
function updateFileStatsDisplay(stats) {
    document.getElementById('totalFiles').textContent = stats.totalFiles;
    document.getElementById('usedFiles').textContent = stats.usedFiles;
    document.getElementById('unusedFiles').textContent = stats.unusedFiles;
    document.getElementById('totalSize').textContent = formatFileSize(stats.totalSize);
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 预览清理
async function previewCleanup() {
    try {
        const token = getAuthToken();
        const response = await fetch('/api/admin/uploads/cleanup/preview', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (response.ok) {
            const result = await response.json();
            if (result.success && result.data) {
                displayCleanupPreview(result.data);
            } else {
                throw new Error(result.error || '预览清理失败');
            }
        } else {
            throw new Error('预览清理失败');
        }
    } catch (error) {
        console.error('预览清理失败:', error);
        showMessage('预览清理失败: ' + error.message, 'error');
    }
}

// 显示清理预览
function displayCleanupPreview(result) {
    const unusedFilesList = document.getElementById('unusedFilesList');
    const unusedFilesContent = document.getElementById('unusedFilesContent');
    
    if (result.unusedFiles.length === 0) {
        unusedFilesContent.innerHTML = '<p>没有发现未使用的文件</p>';
        document.getElementById('executeCleanupBtn').disabled = true;
    } else {
        let html = `<p>${result.message || `发现 ${result.unusedFiles.length} 个未使用的文件`}</p>`;
        html += '<ul class="file-list">';
        result.unusedFiles.forEach(filename => {
            // result.unusedFiles 是字符串数组，每个元素是文件名
            html += `<li>${filename}</li>`;
        });
        html += '</ul>';
        unusedFilesContent.innerHTML = html;
        document.getElementById('executeCleanupBtn').disabled = false;
    }
    
    unusedFilesList.style.display = 'block';
}

// 执行清理
async function executeCleanup() {
    if (!confirm('确定要删除这些未使用的文件吗？此操作不可撤销！')) {
        return;
    }
    
    try {
        const token = getAuthToken();
        const response = await fetch('/api/admin/uploads/cleanup', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (response.ok) {
            const result = await response.json();
            displayCleanupResults(result);
            // 重新加载统计信息
            loadFileStats();
        } else {
            throw new Error('执行清理失败');
        }
    } catch (error) {
        console.error('执行清理失败:', error);
        showMessage('执行清理失败: ' + error.message, 'error');
    }
}

// 显示清理结果
function displayCleanupResults(result) {
    const cleanupResults = document.getElementById('cleanupResults');
    const cleanupResultsContent = document.getElementById('cleanupResultsContent');
    
    let html = `<p>清理完成！删除了 ${result.deletedCount} 个文件，释放空间: ${formatFileSize(result.freedSpace)}</p>`;
    
    if (result.errors && result.errors.length > 0) {
        html += '<p class="error">以下文件删除失败:</p><ul>';
        result.errors.forEach(error => {
            html += `<li>${error}</li>`;
        });
        html += '</ul>';
    }
    
    cleanupResultsContent.innerHTML = html;
    cleanupResults.style.display = 'block';
    
    // 隐藏未使用文件列表
    document.getElementById('unusedFilesList').style.display = 'none';
    document.getElementById('executeCleanupBtn').disabled = true;
    
    showMessage('文件清理完成', 'success');
}

// ==================== 用户管理功能 ====================

// 用户管理分页变量
let currentUserPage = 1;
let userPageSize = 10;

// 加载用户数据
async function loadUsers(page = 1, search = '', role = '', status = '') {
    try {
        showLoading('usersTableBody');
        
        // 如果没有传入参数，从页面元素获取
        if (!search && !role && !status) {
            search = document.getElementById('searchUser')?.value || '';
            role = document.getElementById('filterUserRole')?.value || '';
            status = document.getElementById('filterUserStatus')?.value || '';
        }
        
        // 更新当前页码
        currentUserPage = page;
        
        const params = new URLSearchParams({
            page: page,
            limit: userPageSize
        });
        
        if (search) params.append('search', search);
        if (role) params.append('role', role);
        if (status) params.append('status', status);
        
        const data = await fetchAPI(`/api/users?${params}`);
        
        if (data && data.success) {
            displayUsers(data.data.users || data.data);
            // 如果有分页数据，更新分页组件
            if (data.data.pagination) {
                updatePagination(data.data.pagination, 'usersPagination', loadUsers);
            }
        } else {
            showError(data?.error || '加载用户数据失败');
        }
    } catch (error) {
        console.error('加载用户数据异常:', error);
        showError('加载用户数据异常');
    }
}

// 显示用户数据
function displayUsers(users) {
    const tbody = document.getElementById('usersTableBody');
    
    if (!users || users.length === 0) {
        tbody.innerHTML = '<tr><td colspan="9" style="text-align: center;">暂无用户数据</td></tr>';
        return;
    }
    
    tbody.innerHTML = users.map(user => {
        const avatar = user.avatar || '/uploads/default-avatar.png';
        const role = user.isAdmin ? '管理员' : '普通用户';
        const roleClass = user.isAdmin ? 'admin' : 'user';
        const createdAt = new Date(user.created_at).toLocaleString('zh-CN');
        const lastLogin = user.last_login ? new Date(user.last_login).toLocaleString('zh-CN') : '从未登录';
        
        return `
            <tr>
                <td><input type="checkbox" class="user-checkbox" value="${user.id}"></td>
                <td>${user.id}</td>
                <td><img src="${avatar}" alt="头像" class="user-avatar" style="width: 40px; height: 40px; border-radius: 50%; object-fit: cover;"></td>
                <td>${escapeHtml(user.username)}</td>
                <td>${escapeHtml(user.email || '未设置')}</td>
                <td><span class="role-badge role-${roleClass}">${role}</span></td>
                <td>${createdAt}</td>
                <td>${lastLogin}</td>
                <td>
                    <button class="btn-small btn-primary" onclick="viewUser(${user.id})">查看</button>
                    <button class="btn-small btn-secondary" onclick="editUser(${user.id})">编辑</button>
                    <button class="btn-small btn-secondary" onclick="toggleUserRole(${user.id})">${user.isAdmin ? '降级' : '提升'}</button>
                    <button class="btn-small btn-danger" onclick="deleteUser(${user.id})">删除</button>
                </td>
            </tr>
        `;
    }).join('');
    
    // 初始化全选功能
    const selectAllCheckbox = document.getElementById('selectAllUsers');
    const userCheckboxes = document.querySelectorAll('.user-checkbox');
    
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function() {
            userCheckboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
        });
    }
}

// 显示创建用户模态框
function showCreateUserModal() {
    document.getElementById('userModalTitle').textContent = '创建新用户';
    document.getElementById('userForm').reset();
    document.getElementById('userId').value = '';
    document.getElementById('passwordGroup').style.display = 'block';
    document.getElementById('password').required = true;
    
    // 重置用户头像上传组件
    resetUserAvatarUpload();
    
    // 绑定用户头像上传事件
    setupUserAvatarUpload();
    
    document.getElementById('userModal').style.display = 'block';
}

// 编辑用户
async function editUser(id) {
    try {
        const data = await fetchAPI(`/api/users/${id}`);
        
        if (data && data.success) {
            const user = data.data;
            
            // 填充表单
            document.getElementById('userId').value = user.id;
            document.getElementById('username').value = user.username;
            document.getElementById('email').value = user.email || '';
            document.getElementById('userAvatar').value = user.avatar || '';
            document.getElementById('isAdmin').checked = user.isAdmin;
            document.getElementById('password').value = '';
            document.getElementById('password').required = false;
            
            // 重置并设置用户头像上传组件
            resetUserAvatarUpload();
            setupUserAvatarUpload();
            
            // 如果用户有头像，显示预览
            if (user.avatar) {
                const userAvatarPreviewImg = document.getElementById('userAvatarPreviewImg');
                const userUploadPlaceholder = document.getElementById('userUploadPlaceholder');
                const removeUserAvatarBtn = document.getElementById('removeUserAvatarBtn');
                
                if (userAvatarPreviewImg && userUploadPlaceholder && removeUserAvatarBtn) {
                    userAvatarPreviewImg.src = user.avatar;
                    userAvatarPreviewImg.style.display = 'block';
                    userUploadPlaceholder.style.display = 'none';
                    removeUserAvatarBtn.style.display = 'inline-block';
                }
            }
            
            // 显示模态框
            document.getElementById('userModalTitle').textContent = '编辑用户';
            document.getElementById('passwordGroup').style.display = 'block';
            document.getElementById('userModal').style.display = 'block';
        } else {
            showMessage(data?.error || '获取用户信息失败', 'error');
        }
    } catch (error) {
        console.error('编辑用户异常:', error);
        showMessage('编辑用户异常', 'error');
    }
}

// 查看用户详情
async function viewUser(id) {
    try {
        const data = await fetchAPI(`/api/users/${id}`);
        
        if (data && data.success) {
            const user = data.data;
            
            // 填充详情
            document.getElementById('detailUserId').textContent = user.id;
            document.getElementById('detailUsername').textContent = user.username;
            document.getElementById('detailUserEmail').textContent = user.email || '未设置';
            document.getElementById('detailUserRole').textContent = user.isAdmin ? '管理员' : '普通用户';
            document.getElementById('detailUserCreatedAt').textContent = new Date(user.created_at).toLocaleString('zh-CN');
            document.getElementById('detailUserLastLogin').textContent = user.last_login ? new Date(user.last_login).toLocaleString('zh-CN') : '从未登录';
            
            const avatar = user.avatar || '/uploads/default-avatar.png';
            document.getElementById('detailUserAvatar').src = avatar;
            
            // 显示模态框
            document.getElementById('userDetailModal').style.display = 'block';
        } else {
            showMessage(data?.error || '获取用户信息失败', 'error');
        }
    } catch (error) {
        console.error('查看用户详情异常:', error);
        showMessage('查看用户详情异常', 'error');
    }
}

// 删除用户
async function deleteUser(id) {
    if (!confirm('确定要删除这个用户吗？此操作不可撤销！')) {
        return;
    }
    
    try {
        const data = await fetchAPI(`/api/users/${id}`, 'DELETE');
        
        if (data && data.success) {
            showMessage('用户删除成功', 'success');
            loadUsers(); // 刷新列表
        } else {
            showMessage(data?.error || '删除用户失败', 'error');
        }
    } catch (error) {
        console.error('删除用户异常:', error);
        showMessage('删除用户异常', 'error');
    }
}

// 批量删除用户
async function batchDeleteUsers() {
    const selectedCheckboxes = document.querySelectorAll('.user-checkbox:checked');
    
    if (selectedCheckboxes.length === 0) {
        showMessage('请选择要删除的用户', 'warning');
        return;
    }
    
    const userIds = Array.from(selectedCheckboxes).map(cb => cb.value);
    
    if (!confirm(`确定要删除选中的 ${userIds.length} 个用户吗？此操作不可撤销！`)) {
        return;
    }
    
    try {
        const data = await fetchAPI('/api/users/batch-delete', 'DELETE', { userIds });
        
        if (data && data.success) {
            showMessage(`成功删除 ${data.data.deletedCount} 个用户`, 'success');
            loadUsers(); // 刷新列表
        } else {
            showMessage(data?.error || '批量删除用户失败', 'error');
        }
    } catch (error) {
        console.error('批量删除用户异常:', error);
        showMessage('批量删除用户异常', 'error');
    }
}

// 切换用户权限
async function toggleUserRole(id) {
    try {
        const data = await fetchAPI(`/api/users/${id}/toggle-role`, 'PATCH');
        
        if (data && data.success) {
            showMessage('用户权限更新成功', 'success');
            loadUsers(); // 刷新列表
        } else {
            showMessage(data?.error || '更新用户权限失败', 'error');
        }
    } catch (error) {
        console.error('更新用户权限异常:', error);
        showMessage('更新用户权限异常', 'error');
    }
}

// 处理用户表单提交
async function handleUserSubmit(e) {
    e.preventDefault();
    
    const formData = new FormData(e.target);
    const userId = document.getElementById('userId').value;
    
    const userData = {
        username: formData.get('username'),
        email: formData.get('email'),
        avatar: formData.get('avatar'),
        isAdmin: formData.get('isAdmin') === 'on'
    };
    
    // 只有在创建用户或密码不为空时才包含密码
    const password = formData.get('password');
    if (!userId || password) {
        userData.password = password;
    }
    
    try {
        let data;
        if (userId) {
            // 编辑用户
            data = await fetchAPI(`/api/users/${userId}`, 'PUT', userData);
        } else {
            // 创建用户
            data = await fetchAPI('/api/users', 'POST', userData);
        }
        
        if (data && data.success) {
            showMessage(userId ? '用户更新成功' : '用户创建成功', 'success');
            document.getElementById('userModal').style.display = 'none';
            loadUsers(); // 刷新列表
        } else {
            showMessage(data?.error || (userId ? '更新用户失败' : '创建用户失败'), 'error');
        }
    } catch (error) {
        console.error('用户表单提交异常:', error);
        showMessage('用户表单提交异常', 'error');
    }
}

// HTML转义函数
function escapeHtml(text) {
    const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    return text ? text.replace(/[&<>"']/g, m => map[m]) : '';
}

// 分页组件更新函数
function updatePagination(pagination, containerId, loadFunction) {
    const container = document.getElementById(containerId);
    if (!container || !pagination) {
        return;
    }

    const { current_page, total_pages, total_count, page_size } = pagination;
    
    if (total_pages <= 1) {
        container.innerHTML = '';
        return;
    }

    let paginationHtml = '<div class="pagination">';
    
    // 上一页按钮
    if (current_page > 1) {
        paginationHtml += `<button class="pagination-btn" onclick="loadUsersPage(${current_page - 1})">上一页</button>`;
    } else {
        paginationHtml += '<button class="pagination-btn" disabled>上一页</button>';
    }
    
    // 页码按钮
    const startPage = Math.max(1, current_page - 2);
    const endPage = Math.min(total_pages, current_page + 2);
    
    if (startPage > 1) {
        paginationHtml += '<button class="pagination-btn" onclick="loadUsersPage(1)">1</button>';
        if (startPage > 2) {
            paginationHtml += '<span class="pagination-ellipsis">...</span>';
        }
    }
    
    for (let i = startPage; i <= endPage; i++) {
        if (i === current_page) {
            paginationHtml += `<button class="pagination-btn active">${i}</button>`;
        } else {
            paginationHtml += `<button class="pagination-btn" onclick="loadUsersPage(${i})">${i}</button>`;
        }
    }
    
    if (endPage < total_pages) {
        if (endPage < total_pages - 1) {
            paginationHtml += '<span class="pagination-ellipsis">...</span>';
        }
        paginationHtml += `<button class="pagination-btn" onclick="loadUsersPage(${total_pages})">${total_pages}</button>`;
    }
    
    // 下一页按钮
    if (current_page < total_pages) {
        paginationHtml += `<button class="pagination-btn" onclick="loadUsersPage(${current_page + 1})">下一页</button>`;
    } else {
        paginationHtml += '<button class="pagination-btn" disabled>下一页</button>';
    }
    
    paginationHtml += '</div>';
    paginationHtml += `<div class="pagination-info">共 ${total_count} 条记录，每页 ${page_size} 条，第 ${current_page}/${total_pages} 页</div>`;
    
    container.innerHTML = paginationHtml;
}

// 加载指定页码的用户数据
function loadUsersPage(page) {
    const searchTerm = document.getElementById('searchUser')?.value || '';
    const roleFilter = document.getElementById('filterUserRole')?.value || '';
    const statusFilter = document.getElementById('filterUserStatus')?.value || '';
    
    loadUsers(page, searchTerm, roleFilter, statusFilter);
}

// ==================== API配置管理功能 ====================

// 加载API配置
async function loadApiConfig() {
    console.log('🔄 开始加载API配置...');
    
    try {
        // 获取所有API密钥
        console.log('📡 正在获取API密钥数据...');
        const result = await fetchAPI('/api/api-keys?include_keys=true');
        console.log('📊 API密钥数据获取结果:', result);
        
        // 检查result的结构
        if (!result) {
            console.error('❌ fetchAPI返回null或undefined');
            showMessage('获取API密钥数据失败：返回数据为空', 'error');
            return;
        }
        
        if (result && result.success && result.data && Array.isArray(result.data)) {
            const apiKeys = result.data;
            console.log('✅ 成功获取到API密钥数据，共', apiKeys.length, '条记录');
            console.log('📋 密钥详情:', apiKeys);
            
            // 更新配置状态
            console.log('🔄 正在更新配置状态...');
            updateConfigStatus(apiKeys);
            
            // 填充表单并显示实际密钥值
            console.log('📝 正在填充配置表单...');
            fillConfigForm(apiKeys);
            console.log('✅ API配置加载完成');
        } else {
            console.error('❌ 加载API配置失败，数据结构异常:', result);
            console.log('期望的数据结构: {success: true, data: [...]}');
            console.log('实际收到的数据:', result);
            showMessage('加载API配置失败：数据格式错误', 'error');
        }
    } catch (error) {
        console.error('加载API配置异常:', error);
        showMessage('加载API配置异常', 'error');
    }
}

// 更新配置状态显示
function updateConfigStatus(apiKeys) {
    const statusMap = {
        'deepseek': 'deepseekStatus',
        'volcengine': 'volcengineImageStatus',
        'volcengine_tts': 'volcenttsTtsStatus',
        'openai': 'otherApiStatus',
        'claude': 'otherApiStatus',
        'gemini': 'otherApiStatus'
    };
    
    // 重置所有状态
    Object.values(statusMap).forEach(statusId => {
        const element = document.getElementById(statusId);
        if (element && statusId !== 'otherApiStatus') {
            element.textContent = '未配置';
            element.className = 'section-status status-warning';
        }
    });
    
    // 更新已配置的状态
    apiKeys.forEach(key => {
        const statusId = statusMap[key.provider];
        if (statusId) {
            const element = document.getElementById(statusId);
            if (element) {
                element.textContent = key.is_active ? '已配置' : '已配置(禁用)';
                element.className = key.is_active ? 'section-status status-success' : 'section-status status-warning';
            }
        }
    });
    
    // 检查其他API配置
    const hasOtherApis = apiKeys.some(key => ['openai', 'claude', 'gemini'].includes(key.provider));
    const otherStatusElement = document.getElementById('otherApiStatus');
    if (otherStatusElement) {
        otherStatusElement.textContent = hasOtherApis ? '已配置' : '可选';
        otherStatusElement.className = hasOtherApis ? 'section-status status-success' : 'section-status';
    }
}

// 填充配置表单
function fillConfigForm(apiKeys) {
    console.log('📋 开始填充配置表单，API密钥数据:', apiKeys);
    
    // 清空所有表单字段
    const form = document.getElementById('apiConfigForm');
    if (!form) {
        console.error('❌ 找不到apiConfigForm表单元素');
        return;
    }
    
    const inputs = form.querySelectorAll('input[type="password"], input[type="text"]');
    inputs.forEach(input => {
        if (!input.readOnly) {
            input.value = '';
            input.placeholder = input.placeholder.replace('已配置 - ', '');
        }
    });
    
    // 根据现有密钥填充实际值
    console.log('🔄 开始填充密钥值...');
    apiKeys.forEach(key => {
        console.log('🔑 处理密钥:', key.provider, '名称:', key.name);
        let inputId = '';
        switch (key.provider) {
            case 'deepseek':
                inputId = 'deepseekApiKey';
                // 填充DeepSeek模型配置
                if (key.api_config) {
                    try {
                        const config = typeof key.api_config === 'string' ? JSON.parse(key.api_config) : key.api_config;
                        if (config.model) document.getElementById('deepseekModel').value = config.model;
                    } catch (e) {
                        console.error('解析DeepSeek配置失败:', e);
                    }
                }
                break;
            case 'volcengine':
                inputId = 'volcengineImageKey';
                // 填充火山引擎图片生成模型配置
                if (key.api_config) {
                    try {
                        const config = typeof key.api_config === 'string' ? JSON.parse(key.api_config) : key.api_config;
                        if (config.model) document.getElementById('volcengineImageModel').value = config.model;
                    } catch (e) {
                        console.error('解析火山引擎配置失败:', e);
                    }
                }
                break;
            case 'volcengine_tts':
                // TTS配置比较复杂，需要解析JSON配置
                if (key.api_config) {
                    try {
                        const config = typeof key.api_config === 'string' ? JSON.parse(key.api_config) : key.api_config;
                        if (config.appId) document.getElementById('volcengineTtsAppId').value = config.appId;
                        if (config.cluster) document.getElementById('volcengineTtsCluster').value = config.cluster;
                        if (config.resourceId) document.getElementById('volcengineTtsResourceId').value = config.resourceId;
                        if (config.voiceType) document.getElementById('volcengineTtsVoice').value = config.voiceType;
                        if (config.secretKey) document.getElementById('volcengineTtsSecretKey').value = config.secretKey;
                    } catch (e) {
                        console.error('解析TTS配置失败:', e);
                    }
                }
                // 填充Access Token
                const accessTokenInput = document.getElementById('volcengineTtsAccessToken');
                if (accessTokenInput && key.api_key) {
                    accessTokenInput.value = key.api_key;
                }
                break;
            case 'openai':
                inputId = 'openaiApiKey';
                break;
            case 'claude':
                inputId = 'claudeApiKey';
                break;
            case 'gemini':
                inputId = 'geminiApiKey';
                break;
        }
        
        if (inputId) {
            const input = document.getElementById(inputId);
            // 尝试多个可能的密钥字段
            const keyValue = key.api_key || key.encrypted_key || key.key_value;
            if (input && keyValue) {
                console.log('✅ 填充密钥到输入框:', inputId, '密钥长度:', keyValue.length);
                input.value = keyValue;
                input.placeholder = '已配置';
            } else if (input) {
                console.log('⚠️ 输入框存在但密钥为空:', inputId, '可用字段:', {
                    api_key: key.api_key,
                    encrypted_key: key.encrypted_key,
                    key_value: key.key_value
                });
            } else {
                console.log('❌ 找不到输入框:', inputId);
            }
        }
    });
}

// 处理API配置表单提交
async function handleApiConfigSubmit(e) {
    e.preventDefault();
    await saveApiConfig();
}

// 保存API配置
async function saveApiConfig() {
    console.log('开始保存API配置');
    
    const form = document.getElementById('apiConfigForm');
    if (!form) return;
    
    const formData = new FormData(form);
    const configs = [];
    
    // DeepSeek配置
    const deepseekKey = formData.get('deepseek_key');
    if (deepseekKey && deepseekKey.trim()) {
        configs.push({
            name: 'DeepSeek AI服务',
            provider: 'deepseek',
            api_key: deepseekKey.trim(),
            notes: 'ET项目DeepSeek AI对话服务',
            api_config: {
                model: formData.get('deepseek_model') || 'deepseek-chat',
                temperature: 0.7,
                max_tokens: 800
            }
        });
    }
    
    // 火山引擎图片生成配置
    const volcengineImageKey = formData.get('volcengine_image_key');
    if (volcengineImageKey && volcengineImageKey.trim()) {
        configs.push({
            name: '火山引擎图片生成服务',
            provider: 'volcengine',
            api_key: volcengineImageKey.trim(),
            notes: 'ET项目火山引擎AI图片生成服务',
            api_config: {
                model: formData.get('volcengine_image_model') || 'doubao-seedream-3-0-t2i-250415',
                endpoint: 'https://ark.cn-beijing.volces.com/api/v3/images/generations'
            }
        });
    }
    
    // 火山引擎TTS配置
    const ttsAppId = formData.get('volcengine_tts_app_id');
    const ttsAccessToken = formData.get('volcengine_tts_access_token');
    const ttsSecretKey = formData.get('volcengine_tts_secret_key');
    
    if (ttsAppId && ttsAccessToken && ttsSecretKey) {
        configs.push({
            name: '火山引擎语音合成服务',
            provider: 'volcengine_tts',
            api_key: ttsAccessToken.trim(), // 主密钥使用Access Token
            notes: 'ET项目火山引擎TTS语音合成服务',
            api_config: {
                appId: ttsAppId.trim(),
                accessToken: ttsAccessToken.trim(),
                secretKey: ttsSecretKey.trim(),
                cluster: formData.get('volcengine_tts_cluster') || 'volcano_tts',
                resourceId: formData.get('volcengine_tts_resource_id') || 'volc.tts.default',
                voice: formData.get('volcengine_tts_voice') || 'zh_female_wanqudashu_moon_bigtts',
                endpoint: 'https://openspeech.bytedance.com/api/v1/tts'
            }
        });
    }
    
    // 其他API配置
    const otherApis = [
        { key: 'openai_key', provider: 'openai', name: 'OpenAI服务' },
        { key: 'claude_key', provider: 'claude', name: 'Anthropic Claude服务' },
        { key: 'gemini_key', provider: 'gemini', name: 'Google Gemini服务' }
    ];
    
    otherApis.forEach(api => {
        const key = formData.get(api.key);
        if (key && key.trim()) {
            configs.push({
                name: api.name,
                provider: api.provider,
                api_key: key.trim(),
                notes: `ET项目${api.name}`
            });
        }
    });
    
    if (configs.length === 0) {
        showMessage('请至少配置一个API密钥', 'warning');
        return;
    }
    
    // 显示保存状态
    showConfigStatus('正在保存配置...', 'info');
    
    let successCount = 0;
    let errorCount = 0;
    const results = [];
    
    // 逐个保存配置
    for (const config of configs) {
        try {
            // 检查是否已存在相同提供商的密钥
            const existingResult = await fetchAPI('/api/api-keys');
            let existingKey = null;
            
            if (existingResult && existingResult.success && existingResult.data) {
                existingKey = existingResult.data.find(key => key.provider === config.provider);
            }
            
            let result;
            if (existingKey) {
                // 更新现有密钥
                result = await fetchAPI(`/api/api-keys/${existingKey.id}`, 'PUT', config);
            } else {
                // 创建新密钥
                result = await fetchAPI('/api/api-keys', 'POST', config);
            }
            
            if (result && result.success) {
                successCount++;
                results.push(`✅ ${config.name}: ${existingKey ? '更新' : '创建'}成功`);
            } else {
                errorCount++;
                results.push(`❌ ${config.name}: ${result?.error || '保存失败'}`);
            }
        } catch (error) {
            errorCount++;
            results.push(`❌ ${config.name}: ${error.message}`);
        }
    }
    
    // 显示保存结果
    const statusMessage = `保存完成: ${successCount}个成功, ${errorCount}个失败`;
    showConfigStatus(statusMessage, errorCount > 0 ? 'warning' : 'success');
    
    // 显示详细结果
    const statusPanel = document.getElementById('configStatusPanel');
    const statusContent = document.getElementById('configStatusContent');
    if (statusPanel && statusContent) {
        statusContent.innerHTML = results.map(result => `<div class="status-item">${result}</div>`).join('');
        statusPanel.style.display = 'block';
    }
    
    // 重新加载配置状态
    setTimeout(() => {
        loadApiConfig();
    }, 1000);
    
    if (errorCount === 0) {
        showMessage('所有API配置保存成功！', 'success');
    } else {
        showMessage(`配置保存完成，${errorCount}个配置失败`, 'warning');
    }
}

// 显示配置状态
function showConfigStatus(message, type = 'info') {
    // 可以在这里添加状态显示逻辑
    console.log(`[${type.toUpperCase()}] ${message}`);
}

// 测试所有API密钥
async function testAllApiKeys() {
    console.log('开始测试所有API密钥');
    showMessage('开始测试API密钥...', 'info');
    
    try {
        const result = await fetchAPI('/api/api-keys');
        
        if (result && result.success && result.data) {
            const apiKeys = result.data.filter(key => key.is_active);
            
            if (apiKeys.length === 0) {
                showMessage('没有找到启用的API密钥', 'warning');
                return;
            }
            
            let testResults = [];
            
            for (const key of apiKeys) {
                try {
                    const testResult = await fetchAPI(`/api/api-keys/${key.id}/test`, 'POST');
                    
                    if (testResult && testResult.success) {
                        testResults.push(`✅ ${key.name} (${key.provider}): 测试成功`);
                    } else {
                        testResults.push(`❌ ${key.name} (${key.provider}): ${testResult?.error || '测试失败'}`);
                    }
                } catch (error) {
                    testResults.push(`❌ ${key.name} (${key.provider}): ${error.message}`);
                }
            }
            
            // 显示测试结果
            const statusPanel = document.getElementById('configStatusPanel');
            const statusContent = document.getElementById('configStatusContent');
            if (statusPanel && statusContent) {
                statusContent.innerHTML = `
                    <h5>API密钥测试结果</h5>
                    ${testResults.map(result => `<div class="status-item">${result}</div>`).join('')}
                `;
                statusPanel.style.display = 'block';
            }
            
            showMessage('API密钥测试完成', 'success');
        } else {
            showMessage('获取API密钥列表失败', 'error');
        }
    } catch (error) {
        console.error('测试API密钥异常:', error);
        showMessage('测试API密钥异常', 'error');
    }
}